I'm using Laravel 5.3
and I'm trying to get the authenticated
user's id in the constructor
method so that I can Filter users by specified company as follows:
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); } }
But this does not return the user id
. I even tried Auth::check()
but it doesn't work.
If I move Auth::check()
out of the __construct()
method, this works:
<?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'); } }
But if I also put it into the constructor of HomeController
, this fails!
Any ideas why this fails?
As of 5.3
Auth::check
it will not work in the controller's constructor, this is one of the undocumented changes. So you need to move it to middleware or check controller method, or move your project to 5.2.x.document