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

Has anyone tried Entrust for user role and permissions in Laravel 5?

I want to add and save a user and attach a role to it at the same time. here is 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, although it works on mine databaseSeeder

, but not on my UserController.

+3


source to share


3 answers


I think you have this problem because you never save to 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 only work if you are automatically incrementing your model id using laravel's auto increment feature. If you are using something like uuids to uniquely identify your fields, you must include public $incrementing = false;

inside your model as well.



Make sure you include the HasRole property inside your model.

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

+3


source


I also use "Entrust" to manage my user permissions, but I use the syntax create

to store my Account. Then I use "role () β†’ attach", for example:



$user = User::create($this->userInputs($request));
$user->roles()->attach($request->input('role'));

      

+1


source


I'm using the provided Auth setting that comes with Laravel 5 with my own settings, 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 the App \ Role at the top of the file. Works great for me.

0


source







All Articles