+1 vote
in Laravel by
What are Events in Laravel?

1 Answer

0 votes
by

In Laravel, Events are a way to subscribe to different events that occur in the application. We can make events to represent a particular event like user logged in, user logged out, user-created post, etc. After which we can listen to these events by making Listener classes and do some tasks like, user logged in then make an entry to audit logger of application.

For creating a new Event in laravel, we can call below artisan command:

php artisan make:event UserLoggedIn

This will create a new event class like below:

<?php

namespace App\Events;

use App\Models\User;

use Illuminate\Broadcasting\InteractsWithSockets;

use Illuminate\Foundation\Events\Dispatchable;

use Illuminate\Queue\SerializesModels;

class UserLoggedIn

{

    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**

     * The user instance.

     *

     * @var \App\Models\User

     */

    public $user;

    /**

     * Create a new event instance.

     *

     * @param  \App\Models\User  $user

     * @return void

     */

    public function __construct(User $user)

    {

        $this->user = $user;

    }

}

For this event to work, we need to create a listener as well. We can create a listener like this:

php artisan make:listener SetLogInFile --event=UserLoggedIn

The below resultant listener class will be responsible to handle when the UserLoggedIn event is triggered.

use App\Events\UserLoggedIn;

class SetLogInFile

{

    /**

     * Handle the given event.

     *

     * @param  \App\Events\UserLoggedIn

     * @return void

     */

    public function handle(UserLoggedIn $event)

    {

        //

    }

}

Related questions

0 votes
asked Jun 27, 2023 in Laravel by Robindeniel
+1 vote
asked Jul 11, 2021 in Laravel by rajeshsharma
...