4

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.

Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
Nick
  • 41
  • 1
  • 1
  • 2

3 Answers3

3

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

Harry Geo
  • 1,163
  • 3
  • 10
  • 24
1

I also use "Entrust" for managing my user permissions, but I use create syntax to store my User. Then I use "roles()->attach", like this :

$user = User::create($this->userInputs($request));
$user->roles()->attach($request->input('role'));
Akarun
  • 3,220
  • 2
  • 24
  • 25
0

I am using the provided Auth setup that ships with Laravel 5 with my own adjustments, so I just do the following in Registrar.php:

public function create( array $data )
{
    // Create a new user, and assign it to 'new_user'
    $new_user = User::create( [
        'username'  => $data['username'], //<< Specific to my own db setup
        'email'     => $data['email'],
        'password'  => bcrypt( $data['password'] ),
    ] );

    // Initiate the 'member' Role
    $member = Role::where( 'name', '=', 'member' )->first();
    // Give each new user the role of 'member'
    $new_user->attachRole( $member );

    // Return the new user with member role attached
    return $new_user; //<<Or whatever you do next with your new user
}

You just have to be sure to use App\Role at the top of the file. Works great for me.

DonnaJo
  • 538
  • 6
  • 15