Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 280
Mukul Mantosh Avatar asked Jan 05 '23 08:01

Mukul Mantosh


2 Answers

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
}
like image 92
Gadzhev Avatar answered Jan 13 '23 08:01

Gadzhev


If you need multi auth based on guards, try this package for laravel 5.3 https://github.com/Hesto/multi-auth

like image 24
Hesto Avatar answered Jan 13 '23 10:01

Hesto