Laravel 5.3 构造函数中的身份验证签入返回 false

2022-08-31 00:40:26

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

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

    }

但是,这不会返回用户。我甚至尝试过,但它不起作用。idAuth::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

任何想法为什么这是失败的?


答案 1

文档

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

作为替代方法,您可以直接在控制器的构造函数中定义基于闭包的中间件。在使用此功能之前,请确保您的应用程序运行的是 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);
        });
    }
}

答案 2

由于5.3在控制器的结构中不起作用,因此它是未记录的更改之一。因此,您需要将其移动到中间件或签入控制器方法,或者将项目移动到5.2.x。Auth::check


推荐