4

I have a laravel project with a CalendarService and I inject that service into my controller. In the constructer I do 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

Call to a member function timelogs() on null

About this line of code:

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

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

What is going on here?

3
  • Auth::user() empty means user is not logged in. are you sure the user is logged in? Commented Mar 1, 2017 at 15:46
  • @Saumini Yeah I am sure :) Commented Mar 1, 2017 at 15:47
  • @Nicolas hahaha ja echt retarded code ik heb een groot stuk gerefactored maar Laravel is echt wel retarded ik mag ni eens simpele services da ik heb geschreven injecteren in mijn controller... Commented Mar 1, 2017 at 15:57

2 Answers 2

2

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.

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This will probably throw an error that the method middleware doesnt exist
I don't want to do this in my controller btw I want to keep my controllers as clean as possible
@FrankLucas sorry I thought the first snippet was of the controller. The alternative to this is to inject the CalendarService object in the controller method. Updated.
0

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.