auth用户在重定向方法中返回null

时间:2019-06-16 16:10:10

标签: php redirect registration laravel-5.8

我正在尝试根据用户角色将用户重定向到某些路由,但是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();
        }
    }


}

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

2 个答案:

答案 0 :(得分:0)

只需这样做

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
});

答案 1 :(得分:0)

我知道了:

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