Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel adding data to pivot table while inserting new record

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???

like image 872
Dipendra Gurung Avatar asked Feb 02 '15 09:02

Dipendra Gurung


People also ask

How do I add data to a pivot table in Laravel?

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();

How do I update a pivot table in Laravel?

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.

How do I save a pivot 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); });


1 Answers

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.

like image 107
lukasgeiter Avatar answered Oct 11 '22 08:10

lukasgeiter