搜尋

首頁  >  問答  >  主體

Laravel 5.3 auth 檢查建構子回傳 false

我正在使用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粉769045426P粉769045426404 天前589

全部回覆(2)我來回復

  • P粉277464743

    P粉2774647432023-10-25 11:42:59

    自 5.3 Auth::check 起,它將無法在控制器的建構子中運作,這是未記錄的變更之一。因此,您需要將其移至中間件或檢查控制器方法,或將項目移至 5.2.x。

    回覆
    0
  • P粉489081732

    P粉4890817322023-10-25 00:38:34

    文件

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

    回覆
    0
  • 取消回覆