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

Laravel 5.3 auth check in constructor returning false

我正在使用 Laravel 5.3,我正在尝试在 constructor 方法中获取 已验证 用户的 id,这样我就可以按指定公司筛选用户,如下所示:

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

    }

然而,这并不是 return 用户 id。我什至试过 Auth::check() 但它不起作用。

如果我将 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');
    }
}

然而,如果我把它也放在 HomeController 的构造方法中,这个 会失败

知道为什么会失败吗?

它失败了,因为你在 parent::__construct(); 之后调用了 $this->middleware('auth');。这意味着您的授权中间件未正确加载。

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

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:

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