基于角色的Laravel注册重定向

时间:2017-10-30 18:38:44

标签: php laravel

我有一个供应商和客户登录,它工作正常并重定向到供应商或客户仪表板但是如何在注册后也这样做?

注册控制器

protected $redirectTo = '/';

登录控制器

<?php

public function login(Request $request)
{
    $this->validate($request, [
        'email' => 'required|email',
        'password' => 'required|min:6',
    ]);

    if (Auth::guard('web')->attempt(['email' => $request->email, 'password' => $request->password, 'active' => 1, 'role_id' => 2], $request->remember)) {
        return redirect()->intended(route('customer.dashboard'));
    } elseif (Auth::guard('web')->attempt(['email' => $request->email, 'password' => $request->password, 'active' => 1, 'role_id' => 1], $request->remember)) {
        return redirect()->intended(route('vendor.dashboard'));
    }

    return redirect()->back()->withInput($request->only('email', 'remember'));
}

4 个答案:

答案 0 :(得分:1)

不确定您使用的是哪个版本,我正在发布Laravel 5.7+的答案

注册Laravel后调用此方法:

// Auth\RegisterController
/**
 * The user has been registered.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function registered(Request $request, $user)
{
    // Assign role to $user. Then you can add condition.
    if($user->hasRole('admin'){
       return redirect()->route('xxx');
    }

    return redirect()->route('default');
}

希望它可以为您提供帮助。 祝你好运!

答案 1 :(得分:0)

您可以尝试这样的事情

<?php 

public function login (Request $request) {

    $this->validate($request,[
            'email'=>'required|email',
            'password'=>'required|min:6',
        ]);

    $authenticated = Auth::guard('web')->attempt(['email'=>$request->email,'password'=>$request->password], $request->remember));

        if (!$authenticated) {
            return redirect()->back()->withInput($request->only('email','remember'));
        }

        // We already have a auth user

        $redirectRoute = $this->determineBackendRoute();

        return redirect()->intended(route($redirectRoute));

}

/**
 * Determine currently authenticated users destination backend
 * */
public function determineBackendRoute () {

    $role = auth()->user()->role_id;

    switch ($role) {
        case '1':
            $route = 'vendor.dashboard';
            break;

        case '2':
            $route = 'vendor.dashboard';
            break;

        default:
            $route = 'home';
            break;
    }

    return $route;
}

答案 2 :(得分:0)

在LoginController中覆盖经过身份验证的方法

 protected function authenticated(Request $request, $user)
    {
        //write your logic's here 

         if ($user->role_id == 1) {
            return redirect()->route('write the route name');
        }

        return redirect('/home');
    } 

答案 3 :(得分:0)

执行以下操作:

protected $redirectTo = '/user/home';

如果基于用户类型,请执行条件语句以更改$redirectTo

的值