Laravel 5 and Entrust. How to save user and attach role at the same time

Nick picture Nick · May 2, 2015 · Viewed 9.3k times · Source

Has anyone tried Entrust for User Roles & Permissions in Laravel 5?

I want to add and save user and attach role into it at the same time. here's my code

     $role = Role::where('name','=','admin')->first();
     $user = new User();
     $user->name = Input::get('name');
     $user->email = Input::get('email');
     $user->password = Hash::make(Input::get('password'));
      if($user->save()){
          $user->attachRole($role);
          return redirect('dashboard/users')->with('success-message','New user has been added');
      }

But $user->attachRole($role); won't work though it works on my databaseSeeder but not on my UserController.

Answer

Harry Geo picture Harry Geo · May 19, 2015

I think you have this problem because you never save in the DB. Try something like this.

 $role = Role::where('name','=','admin')->first();
 $user = new User();
 $user->name = Input::get('name');
 $user->email = Input::get('email');
 $user->password = Hash::make(Input::get('password'));
 $user->save()
 $user->attachRole($role);
 return redirect('dashboard/users')->with('success-message','New user has been added');

Of course this method will work only if you auto-increment your model's id using laravel's auto-increment feature. If you are using something like uuids to uniquely identify your fields, you should also include public $incrementing = false; inside your Model.

Make sure you include the HasRole trait inside your model.

Also take a look at Akarun's answer as it will also work.The create method, create's a new instance and also save to db so you don't need to $user->save()