Laravel 5.3 auth 检查构造函数返回 false
P粉769045426
P粉769045426 2023-10-24 20:03:40
0
2
582

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

namespace AppHttpControllers;

use IlluminateFoundationBusDispatchesJobs;
use IlluminateRoutingController as BaseController;
use IlluminateFoundationValidationValidatesRequests;
use IlluminateFoundationAuthAccessAuthorizesRequests;
use IlluminateSupportFacadesView;
use AppModelsUser;
use AppModelsCompany;
use IlluminateSupportFacadesAuth;


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

    }

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

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

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

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

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

但是,如果我也将其放入 HomeController 的构造方法中,则此失败

有什么想法为什么会失败吗?

P粉769045426
P粉769045426

全部回复(2)
P粉277464743

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

P粉489081732

文档

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);
        });
    }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板