Launching Laravel Auth Dependencies ::

I have a laravel project with CalendarService and I inject this service into my controller. In the constructor, I am doing something like this:

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;
}

And I get this error

Calling the member function timelogs () at zero

About this line of code:

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

I used use Illuminate\Support\Facades\Auth;in my service

What's going on here?

+4
source share
2 answers

The problem (as stated at https://laracasts.com/discuss/channels/laravel/cant-call-authuser-on-controllers-constructor ) is the fact that Auth middleware is not initialized during the controller build phase.

Instead, you can do this:

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
}

. , CalendarService .

+1

auth() Auth:: Laravel, .

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

Source: https://habr.com/ru/post/1671152/


All Articles