I have three tables,
roles(id, name); users(id, email, password); user_role(id, user_id, role_id);
In this scenario, I have users table is associated to roles table with many to many relation.
I have two eloquent model as
Role +users(){ belongsToMany('User') } User +roles(){ belongsToMany('Role') }
Now, the question is when I want to add a new user along with ids of roles that I would like to assign to users. How can I insert values to pivot table with Laravel best practices?
My existing code is:-
$roles = Input::get('roles'); // arrays of role ids $user = new User(); $user->username = Input::get('username'); $user->password = Hash::make(Input::get('password')); $user->save();
What to do next???
How can I insert values to pivot table with Laravel best practices? $roles = Input::get('roles'); // arrays of role ids $user = new User(); $user->username = Input::get('username'); $user->password = Hash::make(Input::get('password')); $user->save();
There are many ways to update the pivot table in Laravel. We can use attach(), detach(), sync(), and pivot attribute to update the intermediate table in Laravel.
Route::get('/', function () { $user = \App\User::find(2); $job = \App\Job::with('notifications')->find(3); $job->notifications->is_accepted = 'Y'; // is_accepted is pivot table's column $notification = $user->notifications()->save($job); });
It's really all described in the documentation.
Anyway, here's how you do it:
$user = new User(); $user->username = Input::get('username'); $user->password = Hash::make(Input::get('password')); $user->save(); $user->roles()->attach($roles);
The important part is that you have to save the user before attaching (using attach()
) the roles because otherwise the user doesn't have an id yet to be used in the pivot table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With