我有一个带有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;
这里发生什么事情?
发布于 2017-03-01 15:52:23
问题在于(正如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。
发布于 2017-03-01 15:49:42
在最新版本的Laravel中,不能在构造函数中使用auth()或Auth::,因此需要在方法中直接使用此逻辑。
public function someMethod()
{
$timelogs = Auth::user()->timelogs()->get();https://stackoverflow.com/questions/42536091
复制相似问题