Laravel 5.3登录重定向到多个用户的不同页面

avi*_*ash 6 php laravel laravel-5.3

我有三种不同类型的用户使用Laravel 5.3.我希望他们在登录后重定向到不同的仪表板页面.例如:

用户 - >登录 - >用户仪表板

admin - > login - > admin-dashboard

我创建了一个名为的中间件CheckRole:

public function handle($request, Closure $next)
{
    if($request->user() === null) {
    return response("Insufficient Permissions" , 401);
    }
    $actions = $request->route()->getAction();
    $roles = isset($actions['roles']) ? $actions['roles'] : null;

    if($request->user()->hasAnyRole($roles) || !$roles) {
            return $next($request);
        }
    return response("Insufficient Permissions" , 401);

}
Run Code Online (Sandbox Code Playgroud)

路线

Route::group(['middleware' => ['auth','roles'], 'roles' => 'Admin'],  function () { 
    // Routes here
}
Run Code Online (Sandbox Code Playgroud)

角色运作完美.

现在redirectTo= '';LoginContoller点只有一个视图.我已经检查了文档,我相信这与守卫有关,而后卫没有解释如何设置它.

我也看过multiauth,但我不认为为不同的用户创建不同的表并因此寻找替代答案是明智的.

任何建议将不胜感激.

我的桌子就像:

Table users

id | name | email
---------
1  | John | john@blah.com
2  | Michael | michael@blah.com

Table roles

id | name
---------
1  | Admin
2  | PrivilegedMember
3  | Subscriber

Table user_role

id | user_id | role_id
----------------------
1  |    1    |    1   
2  |    2    |    2
Run Code Online (Sandbox Code Playgroud)

这可能与下面的问题重复,但提供的答案不会解释多个重定向.

Laravel 5.3中的多重身份验证

sep*_*ehr 6

authenticated()在您的实现方法LoginController并在那里添加重定向逻辑:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    // ...

    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     *
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        if($user->hasRole('Admin')) {
            return redirect()->intended('admin');
        } 

        if ($user->hasRole('PrivilegedMember')) {
            return redirect()->intended('PriviligedMember/index');
        }
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

在用户通过身份验证后调用该方法.见最后两行sendLoginResponse:

/**
 * Send the response after the user was authenticated.
 *
 * @param  \Illuminate\Http\Request  $request
 *
 * @return \Illuminate\Http\Response
 */
protected function sendLoginResponse(Request $request)
{
    $request->session()->regenerate();

    $this->clearLoginAttempts($request);

    return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
}
Run Code Online (Sandbox Code Playgroud)

所以它是这种逻辑的完美候选者.

关于你自己答案的另一个注意事项AuthenticatesUser是水平扩展的特性LoginController,你可以安全地覆盖控制器中的任何方法而不触及核心文件.