Home > Blockchain >  insert data with many to many relation in Laravel Eloquent
insert data with many to many relation in Laravel Eloquent

Time:06-19

I have created Many To Many relationships on both levels (database and Models) for (User) and (Role) Models, now how can I assign many roles to the user id = 2 for instance: like below?

       $user = User::find(2);
       ????
        return view('index', compact(''));

CodePudding user response:

By using attach and insert array for multiple roles

$roleId = [1, 2, 3];
$user->roles()->attach($roleId);

There's also sync method, the difference is sync remove all roles associated by user only if its not included in array of roleId

// User has role_id 1, 2, 3
$roleId = [1, 3];
$user->roles()->sync($roleId); // Role id 2 removed

Docs

  • Related