What can we help you with?

If you are interested in finding out more about how we can help your organization, please provide your details and project requirements. We'll get back to you soon.

Steps to Implement Event Handler in Laravel 5.x Development

Laravel

Laravel’s event is easy to implement and provides a simple observer practice. Allowing application user to subscribe and listen to various events that occur in your application. Event classes are saved in ‘App/Events’ folder and listeners are saved in “App/Listeners” folder. In the latest Laravel development, you don’t see these folders in your project. It will create automatically when you generate events and listeners through Artisan console commands.

Events assist as a great way to separate various aspects of your application, it is possible that a single event will have multiple listeners that they don’t depend on each other. For example, you may wish to send notification or email to your user each time purchase any product from your site. Instead of writing your purchase processing code to your notification code, Laravel developer can create an item purchase event, which will listener can receive and send email or notification to the user.

Example of Laravel Events

  • A new user register on our website
  • A comment is added in the blog
  • A user creates a blog post
  • A user like or dislike photos and much more

To Register Events & Listeners

To register your events, you need to open app/Providers/EventServiceProvider.php, you can find the protected listen property on the EventServiceProvider class. Look at the below code.

<?php
protected $listen = [
    'App\Events\Event' => [
        'App\Listeners\EventListener',
    ],
];

The Listen array contains a list of events and listeners and you can add as many events in this array as your application requires. For an example let’s add User Registered event:

<?php
protected $listen = [
    'App\Events\UserRegistered'=> [
            'App\Listeners\SendActivationCode',
            'App\Listeners\AssignRole',
        ]
];

Here, we have created the UserRegistered event so it will be trigger when any user registered. If you want to call some action on new user registered then you can call as many actions as you want. Here I have define two action one is SendActivationCode and another one is AssignRole. Let’s generate events and listeners.

Generate your Events and Listeners

Manually generating the files for events and listeners is very painful. Instead, you can add listeners and events to your EventServiceProvider and run event:generate command.
php artisan event:generate

This command generates any events and listeners that are listed in your EventServiceProvider. Events and listeners which already exist will be untouched.

Define Events

An event class is a data object which holds the information related to the event. For an example, please check below created event class. UserRegistered event receives an Eloquent ORM object.

<?php
namespace App\Events;
use App\User;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
 
class UserRegistered
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $user;
    /**
     * Create a new event instance.
     * @return void   */
    public function __construct(User $user)
    {
        $this->user = $user;
    }
}

You can see that the event class does not contain any logic. SerializesModels trait will be used in the event will respectful serialize any Eloquent models if the event object is serialized using PHP’s serialize function. Here we have pass $user object to construct and that object will assign to $user variable to that class.

Defining Listeners

Now, let’s talk about listeners for our example event. Listeners will receive the event object in their handle method. The php artisan make:listener command will automatically create proper class and type-hint the event on the handle method. Here I am creating two listeners for UserRegistered event. I want to send activation code to user as well as assign role to him. See listeners below.

<?php
namespace App\Listeners;
use App\Events\UserRegistered;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendActivationCode
{
    /*** Create the event listener.
     * @return void
     */
    public function __construct()
    {
        //
    }
    /**
     * Handle the event.
     * @param  UserRegistered  $event
     * @return void
     */
    public function handle(UserRegistered $event)
    {
        \Log::info('activation',['user' => $event->user]);
    }
}

To call the event at the time of user registration, then you need to call this way.

event(new UserRegistered($user));

Here, we have passed $user object which will contain new register user data so it will help us to send activation code and assign a role to him. Currently, I have written Log code when the event is called. So you can write your own code there as per your event type.

To stop action of an Event

If you may wish to stop the action of the event to other listeners then you may need to do so by returning false from your listeners.