构造函数中的 Laravel 5.3 身份验证检查返回 false

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39186222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:22:34  来源:igfitidea点击:

Laravel 5.3 auth check in constructor returning false

phplaravelauthenticationlaravel-5.3

提问by 001221

I'm using Laravel 5.3and I'm trying to get the authenticateduser's idin the constructormethod so I can filter the user by assigned company as follows:

我正在使用Laravel 5.3并尝试在方法中获取经过身份验证的用户idconstructor以便我可以按指定的公司过滤用户,如下所示:

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\View;
use App\Models\User;
use App\Models\Company;
use Illuminate\Support\Facades\Auth;


class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests ;

    public $user;
    public $company;


    public function __construct()
    {


        $companies = Company::pluck('name', 'id');
        $companies->prepend('Please select');
        view()->share('companies', $companies);
        $this->user = User::with('profile')->where('id', \Auth::id())->first();
        if(isset($this->user->company_id)){
            $this->company = Company::find($this->user->company_id);
            if (!isset($this->company)) {
                $this->company = new Company();
            }
            view()->share('company', $this->company);
            view()->share('user', $this->user);
        }

    }

However this doesn't return the user id. I've even tried Auth::check()and it doesn't work.

但是,这不会返回 user id。我什至尝试过Auth::check(),但它不起作用。

If I move the Auth::check()out of the __construct()method then this works as follows:

如果我将方法Auth::check()移出,__construct()则其工作原理如下:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        dd(\Auth::check());
        return view('home');
    }
}

However this failsif I put this in the construct method in the HomeControllertoo!

但是,如果我将它放在构造方法中,这将失败HomeController

Any ideas why this is failing?

任何想法为什么会失败?

回答by ABDEL-RHMAN

docs

文档

you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.

As an alternative, you may define a Closure based middleware directly in your controller's constructor. Before using this feature, make sure that your application is running Laravel 5.3.4 or above:

您无法在控制器的构造函数中访问会话或经过身份验证的用户,因为中间件尚未运行。

作为替代方案,您可以直接在控制器的构造函数中定义基于闭包的中间件。在使用此功能之前,请确保您的应用程序运行的是 Laravel 5.3.4 或更高版本:

class ProjectController extends Controller
{
    /**
     * All of the current user's projects.
     */
    protected $projects;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            $this->projects = Auth::user()->projects;

            return $next($request);
        });
    }
}

回答by Alexey Mezenin

Since 5.3 Auth::checkwill not work in a controller's construtor, it's one of undocumented changes. So, you need to move it to middleware or do check in controller methods instead or move project to 5.2.x.

由于 5.3Auth::check在控制器的构造函数中不起作用,因此它是未记录的更改之一。因此,您需要将其移至中间件或改为检查控制器方法或将项目移至 5.2.x。

回答by Andrej Ludinovskov

It fails because you call $this->middleware('auth');after parent::__construct();. It means that you auth middleware is not loaded properly.

它失败了,因为你$this->middleware('auth');parent::__construct();. 这意味着您的身份验证中间件未正确加载。