构造函数中的 Laravel 5.3 身份验证检查返回 false [英] Laravel 5.3 auth check in constructor returning false
问题描述
我正在使用 Laravel 5.3
并且我正在尝试在 constructor
中获取 经过身份验证的 用户的 id
> 方法,以便我可以按指定的公司过滤用户,如下所示:
I'm using Laravel 5.3
and I'm trying to get the authenticated user's id
in the constructor
method so I can filter the user by assigned 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);
}
}
然而,这不会返回用户 id
.我什至尝试过 Auth::check()
但它不起作用.
However this doesn't return the user id
. I've even tried Auth::check()
and it doesn't work.
如果我将 Auth::check()
移出 __construct()
方法,则其工作方式如下:
If I move the Auth::check()
out of the __construct()
method then this works as follows:
<?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
的构造方法中,这失败!
However this fails if I put this in the construct method in the HomeController
too!
任何想法为什么会失败?
Any ideas why this is failing?
推荐答案
您无法访问会话或经过身份验证的用户控制器的构造函数,因为中间件还没有运行.
you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.
作为替代方案,您可以直接定义一个基于闭包的中间件在控制器的构造函数中.在使用此功能之前,请确保您的应用程序运行的是 Laravel 5.3.4 或更高版本:
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);
});
}
}
这篇关于构造函数中的 Laravel 5.3 身份验证检查返回 false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!