Laravel 5.3中的多重身份验证 [英] Multiple Authentication in Laravel 5.3

查看:94
本文介绍了Laravel 5.3中的多重身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Laravel 5.3中为两个不同的表(用户和管理员)设置多重身份验证.

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

Laravel默认具有用户模型.

By default Laravel has User Model.

推荐答案

看起来您需要实现角色.您可以使用默认的Laravel用户模型,并且需要创建一个角色模型:

Looks like you need to implements roles. You can use the default Laravel User Model and will need to create a Role 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();
}
...

角色模型

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

除了用户表之外,您还需要创建2个表:

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

现在,您可以为拥有的不同角色实现不同的权限.您可以使用策略或Gates定义权限.有关更多信息,请参见文档.

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.

现在要将成员重定向到/users/home,将管理员重定向到/admin/dashboard,您可以执行以下操作:

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

您在AuthServiceProvider中定义adminAccess:

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('/');
}

然后在$routeMiddleware变量中的Kernal.php中注册中间件.然后,您可以将所有管理路由放在一个组中,并在其中使用中间件:

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
}

这篇关于Laravel 5.3中的多重身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆