Search code examples
laravellaravel-5.3entrust

Laravel 5.3 - Best way to implement Entrust role on signup?


I'm working with Laravel 5.3 and I'm trying to set a role when someone signs up, I've used the Zizaco Entrust library.

I'm unsure on the best way to achieve something like this.

I tried to do this inside RegisterController's create method like below:

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

    $user = User::where('email', '=', $data['email'])->first();

    // role attach alias
    $user->attachRole($employee);
}

But obviously that's not right. So I'm a bit unsure on what the best practice is with this sort of thing.


Solution

  • If, as your comment on the OP suggests, you always want to assign the same role to a registered user, you can use a Model Observer for this - it's really simple.

    // app/Observers/UserObserver.php
    
    <?php namespace App\Observers;
    
    use App\Models\User;
    use App\Models\Role; // or the namespace to the Zizaco Role class
    
    class UserObserver {
    
        public function created( User $user ) {
            $role = Role::find( 1 ); // or any other way of getting a role
            $user->attachRole( $role );
    }
    

    Then you simply register the observer in your AppServiceProvider:

    // app/Providers/AppServiceProvider.php
    
    use App\Models\User;
    use App\Observers\UserObserver;
    
    class AppServiceProvider extends Provider {
    
        public function boot() {
            User::observe( new UserObserver );
            // ...
        }
    
        // ...
    
    }