How to Use Laravel Events and Listeners in Your Application

Laravel comes with several cool features at its core. Some of them are Broadcasting, File Storage, Notifications, Events, etc. Each of these built-in features helps developers to simplify common and complicated tasks.

In this article, we discuss Laravel Events which allow us to register a listener for specific events that occur in the application. In other words, I can say user registered, order placed, product added all these are the events. And if you need to trigger some action after these events you can register listeners. Laravel automatically calls the listeners registered for specific events.

For our article, I will implement an event for user registration. Once a user registered to the application, the system should send them 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 into your Laravel application.

Registering Events and Listeners in Laravel

Laravel provides EventServiceProvider file where you need to register your events and listeners. In our case we need to add an event and listener for user registration. So, open the file EventServiceProvider.php and add UserRegistered event in it.

app/Providers/EventServiceProvider.php

...
...
class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'App\Events\UserRegistered' => [
            'App\Listeners\SendWelcomeEmail',
        ],
    ];

The user can add as many events to this array depending on requirements. Next, generate Laravel events by running the command:

php artisan event:generate

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

Defining Events and Listeners

You are now ready with the boilerplate for your user registered event. Our goal is to send a welcome email to the user after they registered. To send an email we need a user object which contains the user’s information. In the UserRegistered event I passed a user object to it’s constructor. This object will then pass to the listener.

app/Events/UserRegistered.php

<?php

namespace App\Events;

....
use App\User;

class UserRegistered
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user;

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

The code which sends an email to a user will go inside the listener file. Open listener SendWelcomeEmail and write the code as follows.

app/Listeners/SendWelcomeEmail.php

<?php

namespace App\Listeners;

....
use Mail;

class SendWelcomeEmail
{
    ....
    ....

    /**
     * Handle the event.
     *
     * @param  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');
            $message->from('noreply@artisansweb.net');
        });
    }
}

In the above file, I wrote the code for sending email in the handle method of the listener class. This is because handle method gets a call after the occurrence of a user registration event.

I also used the first parameter as ’emails.mail’ in the Mail method. It means you should create resources/views/emails/mail.blade.php file.

mail.blade.php

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

<p>{{ $body }}</p>

Finally Call the Event

At this stage, you all set with your event and listener. The last step remains is calling the event from the appropriate place. Let’s say you are using ‘UserController’ for registering a user. So from the UserController, you can give a call to the event as follows.

app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

....
use App\Events\UserRegistered;
use App\User;

class UserController extends Controller
{
    .....
    .....

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $user = User::create([
            'name' => $request->input('name'),
            'email' => $request->input('email'),
            'password' => bcrypt($request->input('password')),
        ]);
 
        // call our event here
        event(new UserRegistered($user));
 
        return $user;
    }
}

Now when a user registered, the above code gives a call to the ‘UserRegistered’ event which eventually calls the listener. The listener then sends a welcome email to the user.

I hope you understand how to use events and listeners in your Laravel application. Please share your thoughts and suggestions in the comment section below.

Related Articles

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

13 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 *