【问题标题】:The auth user returns null in redirect methodauth 用户在重定向方法中返回 null
【发布时间】:2019-06-16 16:10:10
【问题描述】:

我正在尝试根据用户角色将用户重定向到某些路由,但是 auth()->user() 返回 null。这是使用 laravel 5.8 的身份验证。有人可以解释发生了什么吗?我是 php 和 laravel 的新手。

如果您有详细说明这些身份验证过程的资源,请分享

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

use Illuminate\Http\Request;

class RegisterController extends Controller
{

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    //public $redirectTo = '/home';
    protected function redirectTo()
    {
        $role = auth()->user()->role;
        //dd($role);
        if ($role === 'candidate') {
            return '/candidate-register';
        }else if ($role === 'employer') {
            return '/employer_dashboard';
        }else if ($role === 'contractor') {
            return '/contractor_dashboard';
        }
    }

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        try {
            return Validator::make($data, [
                'first_name' => ['required', 'string', 'max:255'],
                'last_name' => ['required', 'string', 'max:255'],
                'role' => ['required', 'string', 'max:50'],
                'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
                'password' => ['required', 'string', 'min:8', 'confirmed'],
            ]);
        } catch (Illuminate\Database\QueryException  $th) {
            return back()->withError($th->getMessage())->withInput();
        }
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(Request $data)
    {
        //$this->validator($data, []);
        try {
            User::create([
                'first_name' => $data['first_name'],
                'last_name' => $data['last_name'],
                'role' => $data['role'],
                'email' => $data['email'],
                'password' => Hash::make($data['password']),
            ]);
            return $this->redirectTo();
        } catch (\Illuminate\Database\QueryException $th) {
            //dd($th->getMessage());
            return redirect('/register')->withError($th->getMessage())->withInput();
        }
    }


}

我希望用户返回到重定向方法中指定的路径

【问题讨论】:

  • 如果这些是 redirectTo 方法中的授权路由,您可能希望首先放置 Auth::check()
  • @ViperTecPro 能不能解释一下,我不懂

标签: php redirect registration laravel-5.8


【解决方案1】:

就这样吧,

protected function redirectTo()
{
        if (Auth::guard()->check() === true) {
            $role = auth()->user()->role;
            if ($role === 'candidate') {
                return '/candidate';
            }else if ($role === 'employer') {
                return '/employer';
            }else if ($role === 'contractor') {
                return '/contractor';
            }
        }
        return '/';
}
protected function create(array $data)
{
   $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'role'  => $data['role'],
            'password' => Hash::make($data['password']),
        ]);
   return $user;
}

这是我用这些路由测试的 web\route.php 文件

Auth::routes();

Route::group([
    'middleware' => 'auth',
    'prefix'     => 'employer'
],function(){
    Route::get('/','HomeController@employerDashboard')->name('employer');
    //......Other routes having employer prefix in the url
});

Route::group([
    'middleware' => 'auth',
    'prefix'     => 'candidate'
],function(){
    Route::get('/','HomeController@candidateDashboard')->name('candidate');
    //......Other routes having employer prefix in the url
});

Route::group([
    'middleware' => 'auth',
    'prefix'     => 'contractor'
],function(){
    Route::get('/','HomeController@contractorDashboard')->name('contractor');
    //......Other routes having contractor prefix in the url
});

【讨论】:

  • 谢谢,您的回复帮助我更好地理解了。
  • 确实如此,我将分享我的修改作为答案
【解决方案2】:

我想通了:

  1. 未导入 Auth 外观,因此它在控制器中不可用,因此返回 null。
  2. 通过控制器中编写的代码,用户正在创建但尚未经过身份验证,因此他们无法访问路由。

我补充说:

  1. 在 RegisterController 中授予访问权限的 Auth 外观
  2. Auth::login($user) 所以用户在注册后通过身份验证

就像我之前提到的,我是该框架的新手,并且正在慢慢地从文档中学习。

查看下面的工作代码:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Auth;


use Illuminate\Http\Request;

class RegisterController extends Controller
{


    use RegistersUsers;


    protected function redirectTo()
    {
       if(Auth::guard()->check() === true){
        $role = auth()->user()->role;

        if ($role === 'candidate') {
            return redirect('candidate-register');
        }else if ($role === 'employer') {
            return redirect('employer-register');
        }else if ($role === 'contractor') {
            return redirect('contractor-register');
        }
       }
        return redirect('register');;
    }

    public function __construct()
    {
        $this->middleware('guest');
    }


    protected function create(Request $data)
    {
        try {

            $this->validate($data, [
                'first_name' => ['required', 'string', 'max:255'],
                'last_name' => ['required', 'string', 'max:255'],
                'role' => ['required', 'string', 'max:50'],
                'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
                'password' => ['required', 'string', 'min:8', 'confirmed'],
            ]);


            $user = User::create([
                'first_name' => $data['first_name'],
                'last_name' => $data['last_name'],
                'role' => $data['role'],
                'email' => $data['email'],
                'password' => Hash::make($data['password']),
            ]);
            Auth::login($user);
            return $this->redirectTo();
        } catch (\Illuminate\Database\QueryException $th) {
            return redirect('register')->withError($th->getMessage())->withInput();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 2017-02-23
    相关资源
    最近更新 更多