Skip to content

How to bind events to models in Laravel 5?

Last updated on February 17, 2018

In this post, I will explain about binding events to models in Laravel 5.Laravel’s Events feature is really cool. It basically allows you to trigger some functions when something is happening on your application.for example when user sign up to the application, the system needs to send a confirmation email to the user. In general most of us will write something like $emailNotification = new EmailNotification; $emailNotification->sendConfirmationEmail($user); , in order to send email to the user. So we can avoid this kind of mess with laravel events and handlers.

Let’s start,

you need to open the app/Providers/EventServiceProvider.php file.

You already have a $listen array, that provides an example:

protected $listen = [
    'event.name' => [
        'EventListener',
    ],
];

Now Let’s create a list of all the events you want to trigger after user sign up.

protected $listen = [
    'App\Events\UserSignup' => [
        'App\Handlers\Events\EmailTheAccountCreatorConfirmationLink',
        'App\Handlers\Events\NotifyTheAdminThatNewAccountHasBeenCreated',
    ],
];

The key in the array is the event and the values are the handlers, where will have actions and we will execute actions.

events and handlers are don’t exist yet, so we need to create events and handlers that we want in our application.

Fortunately, Laravel’s Artisan command allows you to generate all those files with one little command line! Let’s try it out :

php artisan event:generate

You should now see new files in app/Events, and in app/Handlers/Events.

We are almost done, we just need to fire the event, and we need to pass data to event handlers.

Where To Register Event Listeners

Your EventServiceProvider serves as a convenient place to register your model event bindings.

/**
 * Register any other events for your application.
 *
 * @param  \Illuminate\Contracts\Events\Dispatcher  $events
 * @return void
 */
public function boot(DispatcherContract $events)
{
    parent::boot($events);
 
 User::created(function($user) {
    event(new UserSignup($user));
});
 
}

Now open your UserSignup event class and you need to pass the data to the constructor, like this :

// app/Events/UserSignup.php
class UserSignup extends Event {
 
    use SerializesModels;
 
    public $user;
 
    /**
    * Create a new event instance.
    *
    * @return void
    */
    public function __construct($user)
    {
        $this->user = $user;
    }
}

Now you need to use this $user data in the handle method

// app/Handlers/Events/EmailTheAccountCreatorConfirmationLink.php
class EmailTheAccountCreatorConfirmationLink {
    /**
    * Create the event handler.
    *
    * @return void
    */
    public function __construct()
    {
        //
    }
 
    /**
    * Handle the event.
    *
    * @param  user has created  $event
    * @return void
    */
    public function handle(UserSignup $event)
    {
       dd($event->user['attributes']); // This is the array which contains all the user data. Do whatever you want with it
    }
}
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments