Laravel Many to Many attach? - laravel-5

I'm trying to create or attach data to table called "user_votes", but I dunno why the connections between "Vote" and "User" doesn't work.
user_votes table
Schema::create('user_votes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->bigInteger('vote_id')->unsigned();
$table->string('name');
$table->string('page', 100)->nullable();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('vote_id')->references('id')->on('votes');
});
Vote model:
public function user_votes()
{
return $this->belongsToMany(User::class, 'user_votes');
}
User model:
public function user_votes()
{
return $this->belongsToMany(Vote::class, 'user_votes');
}
store controller:
auth()->user()->user_votes()->attach([
'name' => $option->name,
'page' => $option->page
]);
Thanks for any ideas.

Please try the below code hope it will help you.
$voteId = 1;
auth()->user()->user_votes()->attach($voteId => [
'name' => $option->name,
'page' => $option->page
]);

Related

When user creation, assign role_id with UUID

I have a UUID system on my application and when I register a user I have to indicate the rank_id, only I don't know its ID as it is generated from a UUID.
So I use a query but it seems to me disgusting.
Do you have another solution?
I thought about not putting a UUID on the rank table to make it easier but I don't know if it's a good idea to mix uuid and classic id
User::create([
'rank_id' => Rank::select('id')->where('title', 'User')->first()->id,
'username' => $request->input('username'),
'email' => strtolower($request->input('email')),
'password' => Hash::make($request->input('password')),
]);
Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('rank_id')->constrained('ranks');
$table->string('username');
$table->string('email');
$table->string('password');
$table->integer('status')->default(0);
$table->rememberToken();
$table->timestamps();
});
Schema::create('ranks', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('title');
$table->timestamps();
});
For easier access, create a helper class or function and use it.
For example create a directory called app\Helpers and inside create a class called RankHelper. The implementation can be like below:
namespace App\Helpers;
use App\Models\Rank;
class RankHelper
{
public static function getIdByName(string $name): string
{
if (!$rank = Rank::select('id')->where('title', $name)->first()) {
throw new \Exception("No rank with this name found.");
}
return $rank->id;
}
}
Then inside your user creation logic just use it like:
User::create([
'rank_id' => RankHelper::getIdByName('User'),
'username' => $request->input('username'),
'email' => strtolower($request->input('email')),
'password' => Hash::make($request->input('password')),
]);

In Laravel many-to-many relationship, is there a way to update data in a pivot table?

I built two models User and Institution.
How do I update the pivot data between them, after adding additional Pivot columns?
<?php
class User extends Authenticatable
{
public function institutions()
{
$pivots = ['id', 'program_choice', 'session'];
return $this->belongsToMany('App\Institution')
->withPivot($pivots);
}
}
class Institution extends Authenticatable
{
public function users()
{
$pivots = ['id', 'program_choice', 'session'];
return $this->belongsToMany('App\User', 'institution_user')
->withPivot($pivots);;
}
}
Here are the migrations
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->integer('user_id')->unsigned();
$table->rememberToken();
$table->timestamps();
});
}
class CreateInstitutionsTable extends Migration
{
public function up()
{
Schema::create('institutions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
$table->string('city')->nullable();
$table->string('state')->nullable();
$table->string('country')->nullable();
$table->string('address')->nullable();
$table->string('user_id')->nullable();
$table->string('postal_code')->nullable();
$table->timestamps();
});
}
}
This is the what the pivot table looks like
I am able to attach the information to the pivot table
public function storeInstitution(Request $request)
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
$institution_id = $request->input('institution_id');
$user_program_choice = $request->input('program_choice');
$user_session = $request->input('session');
$user_inst = array(
'program_choice' => $user_program_choice,
'session' => $user_session,
'user_id' => $user_id,
'institution_id' => $institution_id
);
$user->institutions()->attach($institution_id, $user_inst);
return 'success';
}
But unable to update the attached pivot E.g I can't change the program_choice, particle physics to something like digital art
Here's my current code
public function updateInstitutions(Request $request, $pivot_id)#TODO id is pivot_id
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
$institution_id = $request->input('institution_id');
$pivot_attributes = array(
'user_id' => $user_id,
'institution_id' => $institution_id,
'session' => $request->input('session'),
'program_choice' => $request->input('program_choice'),
);
$user->institutions()->updateExistingPivots($institution_id, $pivot_attributes, false);
return 'success';
}
How do I update my pivot data, using the pivot id?
Check the documentation regarding this aspect.
Updating A Record On A Pivot Table
If you need to update an existing row in your pivot table, you may use
updateExistingPivot method. This method accepts the pivot record
foreign key and an array of attributes to update:
$user = App\Models\User::find(1);
$user->roles()->updateExistingPivot($roleId, $attributes);

Creating a item with multiple relations in 1 call

So I have a project table:
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('name');
$table->string('reference')->nullable();
$table->date('started')->nullable();
$table->date('ended')->nullable();
$table->string('industry')->nullable();
$table->string('operatives')->nullable();
$table->timestamps();
$table->softDeletes();
});
And I have an hours table:
Schema::create('hours', function (Blueprint $table) {
$table->increments('id');
$table->string('hours');
$table->date('date')->nullable();
$table->text('notes')->nullable();
$table->integer('project_id');
$table->integer('user_id');
$table->softDeletes();
$table->timestamps();
});
Now, is there anyway to create an association with both the project_id and user_id in one call?
I know I can do the following (adding the user_id to the hours):
$hours = [
'hours' => $request->hours,
'date' => $request->date,
'operatives' => $request->operatives,
'notes' => $request->notes,
'user_id' => auth()->user()->id,
];
$create = $project->hours()->save(new $this->hour($hours));
But I am trying to do something like so:
$hours = [
'hours' => $request->hours,
'date' => $request->date,
'operatives' => $request->operatives,
'notes' => $request->notes,
];
$create = $project->hours()->save(auth()->user()->save($hours));
Both user and project have the same hours relation in their classes:
/**
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function hours(): HasMany
{
return $this->hasMany(Hour::class);
}
Is this possible, if so, how would I go about doing it?
I think the best way to handle this would be to separate the saving of Hours as an independent instance of the model and then sync it with both like so:
$hour = Hour::create($hours);
$project->hours()->syncWithoutDetaching([$hour->id]);
$user->hours()->syncWithoutDetaching([$hour->id]);

Not being relationships in laravel 5 db:seed

I have three model Developer model:
migration:
$table->increments('id');
$table->string('email')->unique();
$table->unsignedInteger('programming_language_id');
$table->unsignedInteger('language_id');
$table->timestamps();
and function
class Developer extends Model
{
public function programming_languages() {
return $this->hasMany('App\ProgrammingLanguage');
}
public function languages() {
return $this->hasMany('App\Language');
}
}
ProgrammingLanguage model:migration:
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
and function:
protected $table = 'programming_languages';
public function developers() {
return $this->belongsToMany('App\Developer');
}
Language model: migration:
$table->increments('id');
$table->string('code', 30)->unique();
$table->timestamps();
and function:
public function developers() {
return $this->belongsToMany('App\Developer');
}
I want to make db seeder and being relationships between those. How can i do that?
I am trying: creating a factory DeveloperFactory
$factory->define(App\Developer::class, function (Faker $faker) {
return [
'email' => $faker->unique()->safeEmail,
'programming_language_id' => function () {
return factory(App\ProgrammingLanguage::class)->create()->id;
},
'language_id' => function () {
return factory(App\Language::class)->create()->id;
}
];
});
seed OK, But it doesnot make any relationships. just seed the data.How can i do that by db:seed?
Seed your languages and programming languages tables first, then query for records in the developer seeder.
return [
'email' => $faker->unique()->safeEmail,
'programming_language_id' => App\ProgrammingLanguage::inRandomOrder()->first()->getKey(),
'language_id' => App\Language::inRandomOrder()->first()->getKey()
];

Does not change default value in mysql (laravel 5,5)

this is my code in users tabel (migrations)
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('level')->default('user');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
when I want to change level manually like below code
return User::create([
'level' => 'admin',
'name' => 'emad',
'email' => 'emad#gmail.com',
'password' => bcrypt('123456')
]);
In the level field, the same user value is saved and admin dosent save.
I do not know why?
Judging from the little code here, i would say you haven't added the level column to the fillable model variable.Like so:
protected $fillable = ['level','any_other_field_you_want_to_assign'];
Add this line of code to the top of your User model class
Check the documentation here

Resources