简体   繁体   English

Laravel依赖注入Auth ::

[英]Laravel dependency injection Auth::

I have a laravel project with a CalendarService and I inject that service into my controller. 我有一个带有CalendarService的laravel项目,我将该服务注入到我的控制器中。 In the constructer I do something like this: 在构造中我做了这样的事情:

CalendarService.php 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 HomeController.php

/** @var CalendarService */
protected $calenderService;

public function __construct
(
    CalendarService $calendarService
)
{
    $this->calenderService = $calendarService;
}

And I get this error 我得到了这个错误

Call to a member function timelogs() on null 在null上调用成员函数timelogs()

About this line of code: 关于这行代码:

Auth::user()->timelogs()->get();

I have used the use Illuminate\\Support\\Facades\\Auth; 我用过use Illuminate\\Support\\Facades\\Auth; in my service 在我的服务中

What is going on here? 这里发生了什么?

The issue is (as pointed out in https://laracasts.com/discuss/channels/laravel/cant-call-authuser-on-controllers-constructor ) the fact that the Auth middleware is not initialized during the controller construction phase. 问题是(如https://laracasts.com/discuss/channels/laravel/cant-call-authuser-on-controllers-constructor中所指出的)Auth中间件在控制器构建阶段未初始化的事实。

You can instead do this though: 你可以这样做:

protected $calenderService;

public function __construct()
{ 
    $this->middleware(function ($request,$next) {        
         $this->calenderService = resolve(CalendarService::class);
         return $next($request);
     });
}

Alternative 替代

public function controllerMethod(CalendarService $calendarService) { 
    //Use calendar service normally
}

Note: This assumes that you're able to resolve the CalendarService via the service container. 注意:这假设您可以通过服务容器解析CalendarService

You can't use auth() or Auth:: in a constructor in the latest versions of Laravel, so you'll need to use this logic directly in the method. 您不能在最新版本的Laravel中的构造函数中使用auth()Auth:: ,因此您需要在方法中直接使用此逻辑。

public function someMethod()
{
    $timelogs = Auth::user()->timelogs()->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM