3

When I ask if(Auth::user()->role == "xxxx") inside CandidateEvent displays "Trying to get property of non-object"

The problem is that component Auth::user() isn't working in my Event.

What is the correct way to use Auth within Events?

public function __construct()
{
    if(Auth::user()->role == "XXXX")
    {
        $candidate = count(Candidate::CountNewCandidate());
    }
    else
    {
        $candidate = count(Candidate::CountNewCandidateGroup());
    }
    $this->data = [ 'cCandidate' => $candidate ];        
}

4 Answers4

5

If there is no authenticated user Auth::user() will return null, so Auth::user()->role will raise the Trying to get property of non-object; Try to check if there is an authenticated user by using Auth::check() then you can check the role :

public function __construct()
{
    if(auth()->check() && auth()->user()->role == "XXXX")
    {
        $candidate = count(Candidate::CountNewCandidate());
    }
    else
    {
        $candidate = count(Candidate::CountNewCandidateGroup());
    }
    $this->data = [ 'cCandidate' => $candidate ];        
}

Note: I used the helper function auth().

I hope this will help you.

Ismail RBOUH
  • 10,292
  • 2
  • 24
  • 36
2

The reason Auth::user() is null in an event (particularly if it is queued), is because there is no user. The authentication data is typically stored in a session and when your even is triggered there is no session variable therefore no session data.

In the past I have passed in the user in the event, then to authenticate the user within the event handler I would call:

\Auth::attempt(['email', $event->performedBy()->email]);

This was necessary because my application had many functions tightly coupled with Authentication (instead of a UserInterface). Ideally I could have just passed in the user as a dependency.

ajon
  • 7,868
  • 11
  • 48
  • 86
0

It looks like you didn't import the namespace for the Auth facade. You have to add it in the declarations

use Illuminate\Support\Facades\Auth;
Jesús Amieiro
  • 2,443
  • 21
  • 15
0

I solved it passing the user to event, through data in the routes:

  Route::group(['middleware' => ['xxxx']], function () {
    event(new NameEvent($data));
    Route::auth();
});