Laravel. Factory model. Many-to-many relationship

I have a problem with a many-to-many relationship on a factory model.

For example:
There are tables users

, roles

and user_role

. I have identified model plants for user

and roles

. Then I try to add a role to the user:

$role = factory(Role::class)->create();
config(['admin_group_id' => $role->id]);
$admin = factory(User::class)->create();
$admin->roles()->save($role);

      

It works, but when I receive $admin->roles()->first()->id

it is not equal$role->id

+3


source to share


1 answer


Instead of using, save()

you should use attach()

and pass the role id



+2


source







All Articles