Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get authenticated user in event listener - Laravel

I am trying to identify proper way to to get authenticated user's information in the event listener.

I can alway use \Auth:user() which seems to work but I don't think it will work if I queue the listener.

Do I need to add the authenticated user to the event class as property for each event, or is there any other way to do this?

like image 811
Ankit Avatar asked Nov 20 '25 15:11

Ankit


1 Answers

Pass the user through the event. You should have access to the Auth facade when the event is triggered.

Event:

class SomeEvent
{
    // Public so that it will be accessible from the listener
    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }
}

Listener:

class SomeListener
{
    public function handle(SomeEvent $event)
    {
        // Get the public property `$user` from the event
        $authUser = $event->user;
    }
}

Trigger:

event(new SomeEvent(auth()->user()));
like image 168
DevK Avatar answered Nov 22 '25 06:11

DevK