Multiple Authentication in Laravel 5.3

醉酒当歌 提交于 2019-11-27 16:55:39

问题


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

By default Laravel has User Model.


回答1:


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
}



回答2:


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



来源:https://stackoverflow.com/questions/39543967/multiple-authentication-in-laravel-5-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!