How to use Laravel Events and Listeners in Your Application

Laravel ships with several nice features to simplify development. Broadcasting, File Storage, Notifications, and Events are some of them. Each of these features helps developers to create a more robust application.

In this article, we discuss Laravel Events which allow you to register a Listener when a certain action occurs. A user registered, an order placed, product added are examples of events. To trigger the action on these events, you need to register the listener. Then Laravel automatically calls the listeners when the event takes place.

The benefit of using this approach is that you can decouple the code. One event can have multiple listeners and you will divide the code across various files(listeners) instead of writing in one place.

For this article, I will implement an event for user registration. Once a user registered for the application, the system should send a welcome email. Here user registration is the event and sending a welcome email is a listener.

Having said that, let’s see how to use events and listeners in your Laravel application.

Registering Events and Listeners in Laravel

Laravel provides the EventServiceProvider where you have to register the events and listeners. In our case, we need to add an event and listener for user registration. Open the EventServiceProvider.php and add an UserRegistered event and SendWelcomeEmail listener to it.

app/Providers/EventServiceProvider.php

use App\Events\UserRegistered;
use App\Listeners\SendWelcomeEmail;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array<class-string, array<int, class-string>>
     */
    protected $listen = [
        UserRegistered::class => [
            SendWelcomeEmail::class,
        ],

    ];

    ...
    ...
}

Next, generate Laravel events by running the command:

php artisan event:generate

This command creates ‘Events’ and ‘Listeners’ directories under the ‘app’ folder. Inside the app/Events directory, you will find the UserRegistered.php file. Similarly, the SendWelcomeEmail.php file is in the app/Listeners directory.

The user can add as many events to the $listen array. One can get a list of all events of applications using the Artisan command:

php artisan event:list

Defining Events and Listeners

We are ready with the files of the event and listener. Our goal is to send a welcome email to the user after they registered. To send an email we require the user object containing the user’s information. I’ll pass the user object to the constructor of the UserRegistered class. This user object will then pass to the listener.

app/Events/UserRegistered.php

<?php

namespace App\Events;

use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use App\Models\User;

class UserRegistered
{
    use Dispatchable, SerializesModels;

    public $user;

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

Next, let’s write the code to send an email to the listener. Open the SendWelcomeEmail and add the code as follows.

app/Listeners/SendWelcomeEmail.php

<?php

namespace App\Listeners;

use App\Events\UserRegistered;
use Mail;

class SendWelcomeEmail
{
    /**
     * Handle the event.
     *
     * @param  \App\Events\UserRegistered  $event
     * @return void
     */
    public function handle(UserRegistered $event)
    {
        $data = array('name' => $event->user->name, 'email' => $event->user->email, 'body' => 'Welcome to our website. Hope you will enjoy our articles.');
 
        Mail::send('emails.mail', $data, function($message) use ($data) {
            $message->to($data['email'])
                    ->subject('Welcome to our Website');
        });
    }
}

In the above file, I wrote the code in the handle method of the listener class. This is because the handle method gets executed once the user registration event happens.

I also used the first parameter as emails.mail in the Mail method. It means you should create a resources/views/emails/mail.blade.php file. After creating a file, add the below code to it.

Hi <strong>{{ $name }}</strong>,
 
<p>{{ $body }}</p>

For the basic purpose, I am using a different approach to shooting an email. If you wish to use mailable then adjust the code accordingly.

Dispatching Events

At this stage, we have added the code for the event and listener. The last step remains to call the event from the appropriate place. Let’s say you are using UserController for registering a user. Inside the UserController, you can trigger the event as follows.

app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Events\UserRegistered;
use App\Models\User;

class UserController extends Controller
{
    public function store(Request $request)
    {
        $user = User::create([
            'name' => $request->input('name'),
            'email' => $request->input('email'),
            'password' => bcrypt($request->input('password')),
        ]);
 
        // trigger the event
        UserRegistered::dispatch($user);
 
        return $user;
    }
}

Now when the user is registered, it dispatches the UserRegistered event which eventually executes the listener. The listener then sends a welcome email to the user. To the event, I passed the $user variable which contains the user’s information.

I hope you understand how to use events and listeners in the Laravel application. I’d recommend using this feature wherever possible to organize the code efficiently. Check out also the official documentation on Events.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

14 thoughts on “How to use Laravel Events and Listeners in Your Application

  1. I am a web developer for the last two years. I don’t get the confidence of full understanding that what is even and listener in laravel. now when I clearly read this article I fully understand and command and very happy. thank you man for the special article. thanks

Leave a Reply

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