Custom Events with Laravel 5 ­ Part 1

Written by: Sharath Shambu | December 18th, 2015

Category: Laravel, Php

It is easy to write custom events and handlers, but writing your own events will allow a lot more flexibility in your application. So let’s get to it! Introduction In this tutorial we will work with a simple application that allows users to create their own Posts and then the Admin can review and approve them. When a user creates a Post, the Admin will get a notification email for the same. Similarly, when the Admin approves the Post, the User will get a notification email. For these two cases we will need to register two events which are PostWasCreated and PostWasApproved. Their respective handlers will be NotifyAdmin and NotifyPostOwner. Hands On Lets begin with registering our first event and its handler. Laravel provides us with an EventServiceProvider, all the events are registered here. /** * Register our events inside the $listen array. */ protected $listen = [ ‘App\Events\PostWasCreated’ => [ ‘App\Listeners\NotifyAdmin’ ], ]; Now, after registering the event we need to define it. Note that we have not created any classes yet for our event. To do that we will be using the Artisan Command “php artisan event:generate”. After running this command you will notice Classes for both, our event and its handler is created under “App\Events” and “App\Listeners” respectively. As mentioned in the Laravel docs, the event class “App\Events\PostWasCreated” is nothing but a placeholder for the event. “An event class is simply a data container which holds the information related to the event.” Our PostWasCreated would pretty much look like this namespace App\Events;

Comments

comments

Leave Comment

We would love to hear from you and we appreciate the good and the bad.

Comments