Table of Contents

Introduction

Laravel provides a simple mechanism for events and listeners so that whenever you want to subscribe or listen to any event of your application, you can do it easily. You can register events with their listeners and decide what you want them to do after a particular action. For example, whenever a new order is created, we wish to send a mail or SMS to the seller. To simplify, we can say an event is an action taken in the application, and the listener is the operation that responds to the event.

In this tutorial, we will learn and explore Laravel 8 events and listeners. We will develop a small demo application in which we will send an email whenever a user is created. In this scenario, we can say user creation is an event, and the listener will send an email on listening to the event.

Tutorial Goal: Laravel 8 Event and Listener

Before getting started with the development part, let’s see what we are building in this tutorial.

Register Event and Listener

The first step is to register the event and the respective listener. For that, Laravel provides an EventServiceProvider.php file where you can define events and listeners.

The $listen property contains an array for registering all the events and listeners as key-value pairs. Define events and listeners as shown below.

// EventServiceProvider.php

Copy Text
protected $listen = [
   Registered::class => [
     SendEmailVerificationNotification::class,
   ],
   'App\Event\UserCreated' => [
     'App\Listeners\SendEmail'
   ]
];

Once you register the event and listener, run the below command to create the files for the respective event and listener.

Copy Text
php artisan event:generate

The above command will generate two files, namely:

  • UserCreated in app/Events
  • SendEmail in app/Listeners

Once done with the Laravel 8 events and listeners setup, now it’s time to get our hands on the logic part.

Define Event Logic

In this section, we will define the action (event) on which we want the set of logic to be performed by the listener; in our demo app, the action is creating a user.

Open App\Events\UserCreated.php and use the below code to pass the actual email address as $email to the __construct method of the UserCreated class

// App\Events\UserCreated.php

Copy Text
public $email;
 public function __construct($email)
 {
   $this->email = $email;
 }

The entire file will look like this.

Copy Text
namespace App\Event;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class UserCreated implements ShouldQueue
{
    use Dispatchable, InteractsWithSockets, SerializesModels;7i

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

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

Here we inherit the ShouldQueue interface using class UserCreated implements ShouldQueue.It will automatically place the logic in the queue.

Define Listener Logic: handle() method

Here, we will write actual logic for sending an email whenever the user is created. In App\Listeners\SendEmail.php, pass the UserCreated $event parameter to handle() method so that we can have a value from the event. The logic within the handle() method will be executed whenever the event is called.

Copy Text
public function handle(UserCreated $event)
 {
  print_r($event->email);
  //We can send a mail from here
  echo ".. From Listeners";
  exit;
 }

Dispatch Event

After creating the event and listener, now it’s time to dispatch the event. It’s pretty straightforward; you just need to pass the event class object to the event() method.

// UserController.php

Copy Text
event (new UserCreated(“[email protected]”));

GitHub Repository: Laravel 8 Events and Listeners

Feel free to clone the repository and play around with the code. You can find the source code here.

Conclusion

I hope the tutorial Laravel 8 Events and Listeners with Example was helpful for you. For any queries and suggestions, feel free to contact us. If you are a Laravel enthusiast, you must check out the Laravel tutorials page, where we provide various tutorials with the source code.

Are you looking for skilled and experienced Laravel developers with optimum problem-solving skills? If yes, then you are just a click away from hiring the best laravel developers! Contact us today and hire Laravel developer for your project.

Hire Laravel Developer

Connect Now

Build Your Agile Team

Hire Skilled Developer From Us

[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?