[英]Laravel dependency injection Auth::
我有一个带有CalendarService的laravel项目,我将该服务注入到我的控制器中。 在构造中我做了这样的事情:
CalendarService.php
/** @var Collection|Timelog[] */
private $timelogs;
public function __construct()
{
$this->currentRoute = URL::to( '/' ) . "/home";
$this->timelogs = Auth::user()->timelogs()->get();
$this->currentDay = 0;
}
HomeController.php
/** @var CalendarService */
protected $calenderService;
public function __construct
(
CalendarService $calendarService
)
{
$this->calenderService = $calendarService;
}
我得到了这个错误
在null上调用成员函数timelogs()
关于这行代码:
Auth::user()->timelogs()->get();
我用过use Illuminate\\Support\\Facades\\Auth;
在我的服务中
这里发生了什么?
问题是(如https://laracasts.com/discuss/channels/laravel/cant-call-authuser-on-controllers-constructor中所指出的)Auth中间件在控制器构建阶段未初始化的事实。
你可以这样做:
protected $calenderService;
public function __construct()
{
$this->middleware(function ($request,$next) {
$this->calenderService = resolve(CalendarService::class);
return $next($request);
});
}
替代
public function controllerMethod(CalendarService $calendarService) {
//Use calendar service normally
}
注意:这假设您可以通过服务容器解析CalendarService
。
您不能在最新版本的Laravel中的构造函数中使用auth()
或Auth::
,因此您需要在方法中直接使用此逻辑。
public function someMethod()
{
$timelogs = Auth::user()->timelogs()->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.