Search code examples
laravellaravel-5.3

Multiple Authentication in Laravel 5.3


How to setup multiple authentication in Laravel 5.3 for two different tables(Users and Admin).

By default Laravel has User Model.


Solution

  • Looks like you need to implements roles. You can use the default Laravel User Model and will need to create a Role Model:

    User Model

    ...
    public function role() {
        return $this->belongsToMany('App\User', 'user_roles', 'role_id', 'user_id');
    }
    
    public function inRole($role) {
        return (bool) $this->role()->where('name', '=', $role)->count();
    }
    ...
    

    Role Model

    ...
    public function users() {
        return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');
    }
    ...
    

    You gonna need to create 2 tables in addition to your users table:

    Table users
    
    id | name
    ---------
    1  | John
    2  | Michael
    
    Table roles
    
    id | name
    ---------
    1  | Admin
    2  | Member
    
    Table user_roles
    
    id | user_id | role_id
    ----------------------
    1  |    1    |    1   
    2  |    2    |    1
    

    Now you can implement different permissions for the different roles you have. You can define the permissions using Policies or Gates. For more info how to do that check the documentation.

    Now to redirect your members to /users/home and admins to /admin/dashboard you can do the following:

    You define adminAccess in your AuthServiceProvider:

    public function boot() {
        $this->registerPolicies();
        ...
    
        // Define adminAccess
        Gate::define('adminAccess', function ($user) {
            return $user->inRole('admin');
        });
    }
    

    Update: Now you can protect your admin routes with a Middleware like so:

    public function handle($request, Closure $next) {
        if (Auth::check() && Auth::user()->inRole('admin')) {
            return $next($request);
        }
    
        return redirect('/');
    }
    

    Then register the Middleware in your Kernal.php in the $routeMiddleware variable. Then you can place all your admin routes in a group and use the middleware there:

    Route::group(['middleware' => 'auth']) {
        // Define your routes
    }