Laravel Events Introduction With Example

|
| By Webner

Laravel Events

Events are one of the many powerful features of the Laravel. The event basically means the thing that happens or takes place, especially the one that is important. So, in Laravel’s case, events are triggered when some condition is met like most websites have authentication systems in which new users are registered. So, if any new users are registers, we want to send them the welcome email. For this scenario, Laravel events come into use. But events as such cannot do anything. They need listeners to perform their actions. Listeners are registered under the events and act accordingly when their events are triggered.

Where are Events and Listeners stored?

By default, events and listeners are stored in the app directory. But if you do not see that directory under the app folder then you have to create that directory first. It is created whenever users created their first event and listeners.
For example

Command to make events:

php artisan make:event EventName

An event holds the data which is going to fire. For example, if the user is registered on the website and we want to send a welcome email to the user –

<?php

namespace App\Events;

use App\Events;
use Illuminate\Queue\SerializesModels;

class SendEmail
{
    use SerializesModels;

    public $user;

    /**
     * Create a new event instance.
     *
     * @param  \App\User  $user
     * @return void
     */
    public function __construct(User $user)
    {
	$this->user = $user;
     }
}

In this code, no information on code that is how to proceed further is given. So, now comes the listener which will play an important role in this situation.

Listeners contain the method named handle which contains the instance of the event which in this case is SendEmail instance.

<?php

namespace App\Listeners;

use App\Events\SendEmail;

class SendWelcomeEmail
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  \App\Events\SendEmail  $event
     * @return void
     */
    public function handle(WelcomeEmail $event)
    {
$newUser = $event->user;
        Mail::send('emails.welcomeUser', ['user' => $newUser], function ($welcomeMessage) use ($newUser) {
                $welcomeMessage->from('welcome@email.com', 'Test User’');
                $welcomeMessage->subject('Welcome '.$newUser>name.'!');
                $welcomeMessage->to($newUser>email);
        });

        // Access the order using $event->order...
    }
}

Generating Events and Listeners –

  1. Register the Events and Listeners –
    You can register events along with listeners in the EventServiceProvider.php file.
    For example –

    protected $listen = [
        'Illuminate\Auth\Events\SendEmail => [
            'App\Listeners\SendWelcomeEmail',
        ],
    ];
    

    Note – Users can also register multiple listeners under one event.

  2. Command to generate all the events and listeners registered in EventServiceProvider.php

    php artisan event:generate

    This command will generate all the corresponding events and listeners mentioned above in App\Events and App\Listeners directories respectively.

Leave a Reply

Your email address will not be published. Required fields are marked *