Advertisement
  1. Code
  2. PHP
  3. Laravel

Custom Events in Laravel

Scroll to top
Read Time: 11 min

In this article, we are going to explore the basics of event management in Laravel. We'll also create a real-world example of a custom event and listener.

The concept of events in Laravel is based on a very popular software design pattern—the observer pattern. In this pattern, the system raises events when something happens, and you can define listeners that listen to these events and react accordingly. It's a really useful feature that allows you to decouple components in a system that otherwise would have resulted in tightly coupled code.

For example, let's say you want to notify all modules in a system when someone logs into your site. Thus, it allows them to react to this login event, whether it's about sending an email or an in-app notification, or for that matter anything that wants to react to this login event.

Basics of Events and Listeners

In this section, we'll explore Laravel's way of implementing events and listeners in the core framework. If you're familiar with the architecture of Laravel, you probably know that Laravel implements the concept of a service provider, which allows you to inject different services into an application.

Similarly, Laravel provides a built-in EventServiceProvider.php class that allows us to define event listener mappings for an application.

Go ahead and pull in the app/Providers/EventServiceProvider.php file.

1
<?php
2
3
namespace App\Providers;
4
5
use Illuminate\Auth\Events\Registered;
6
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
7
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
8
use Illuminate\Support\Facades\Event;
9
10
class EventServiceProvider extends ServiceProvider
11
{
12
    /**

13
     * The event listener mappings for the application.

14
     *

15
     * @var array

16
     */
17
    protected $listen = [
18
        Registered::class => [
19
            SendEmailVerificationNotification::class,
20
        ],
21
    ];
22
23
    /**

24
     * Register any events for your application.

25
     *

26
     * @return void

27
     */
28
    public function boot()
29
    {
30
        parent::boot();
31
32
        //

33
    }
34
}

Let's have a close look at the $listen property, which allows you to define an array of events and associated listeners. The array keys correspond to events in a system, and their values correspond to listeners that will be triggered when the corresponding event is raised in a system.

I prefer to go through a real-world example to demonstrate it further. As you probably know, Laravel provides a built-in authentication system which facilitates features like login, register, and the like.

Assume that you want to send an email notification, as a security measure, when someone logs into the application. If Laravel didn't support the event listener feature, you might have ended up editing the core class or using some other method to plug in your code that sends an email.

In fact, you're on the luckier side as Laravel helps you to solve this problem using the event listener. Let's revise the app/Providers/EventServiceProvider.php file to look like the following.

1
<?php
2
3
namespace App\Providers;
4
5
use Illuminate\Auth\Events\Registered;
6
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
7
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
8
use Illuminate\Support\Facades\Event;
9
use App\Listeners\SendEmailNotification;
10
11
class EventServiceProvider extends ServiceProvider
12
{
13
    /**

14
     * The event listener mappings for the application.

15
     *

16
     * @var array

17
     */
18
    protected $listen = [
19
        Registered::class => [
20
            SendEmailVerificationNotification::class,
21
        ],
22
        Illuminate\Auth\Events\Login::class => [
23
            SendEmailNotification::class,
24
        ]
25
    ];
26
27
    /**

28
     * Register any events for your application.

29
     *

30
     * @return void

31
     */
32
    public function boot()
33
    {
34
        parent::boot();
35
36
        //

37
    }
38
}

Illuminate\Auth\Events\Login is an event which will be raised by the Auth plugin when someone logs into an application. We've bound that event to the App\Listeners\SendEmailNotification listener, so it'll be triggered on the login event.

Of course, you need to define the App\Listeners\SendEmailNotification listener class in the first place. As always, Laravel allows you to create a template code of a listener using the artisan command.

1
php artisan event:generate

This command generates event and listener classes listed under the $listen property.

In our case, the Illuminate\Auth\Events\Login event already exists, so it only creates the App\Listeners\SendEmailNotification listener class. In fact, it would have created the Illuminate\Auth\Events\Login event class too if it didn't exist in the first place.

Let's have a look at the listener class created at app/Listeners/SendEmailNotification.php.

1
<?php
2
3
namespace App\Listeners;
4
5
use App\Providers\Illuminate\Auth\Events\Login;
6
use Illuminate\Contracts\Queue\ShouldQueue;
7
use Illuminate\Queue\InteractsWithQueue;
8
9
class SendEmailNotification
10
{
11
    /**

12
     * Create the event listener.

13
     *

14
     * @return void

15
     */
16
    public function __construct()
17
    {
18
        //

19
    }
20
21
    /**

22
     * Handle the event.

23
     *

24
     * @param  Login  $event

25
     * @return void

26
     */
27
    public function handle(Login $event)
28
    {
29
        //

30
    }
31
}

It's the handle method which will be invoked with appropriate dependencies whenever the listener is triggered. In our case, the $event argument should contain contextual information about the login event—logged-in user information.

And we can use the $event object to carry out further processing in the handle method. In our case, we want to send an email notification to the logged-in user.

The revised handle method may look something like:

1
public function handle(Login $event)
2
{
3
    // get logged in user's email and username

4
    $email = $event->user->email;
5
    $username = $event->user->name;
6
     
7
    // send email notification about login

8
}

So that's how you're supposed to use the events feature in Laravel. In the next section, we'll create a custom event and an associated listener class.

Create a Custom Event

The example scenario which we're going to use for our example is something like this:

  • An application needs to clear caches in a system at certain points. We'll raise the CacheClear event along with the contextual information when an application does the aforementioned. We'll pass cache group keys along with an event that was cleared.
  • Other modules in a system may listen to the CacheClear event and would like to implement code that warms up related caches.

Let's revisit the app/Providers/EventServiceProvider.php file and register our custom event and listener mappings.

1
<?php
2
3
namespace App\Providers;
4
5
use Illuminate\Auth\Events\Registered;
6
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
7
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
8
use Illuminate\Support\Facades\Event;
9
use App\Listeners\WarmUpCache;
10
use App\Events\ClearCache;
11
12
class EventServiceProvider extends ServiceProvider
13
{
14
    /**

15
     * The event listener mappings for the application.

16
     *

17
     * @var array

18
     */
19
    protected $listen = [
20
        Registered::class => [
21
            SendEmailVerificationNotification::class,
22
        ],
23
        ClearCache::class => [
24
            WarmUpCache::class,
25
        ],
26
    ];
27
28
    /**

29
     * Register any events for your application.

30
     *

31
     * @return void

32
     */
33
    public function boot()
34
    {
35
        parent::boot();
36
37
        //

38
    }
39
}

As you can see, we've defined the App\Events\ClearCache event and associated listener class App\Listeners\WarmUpCache under the $listen property.

Next, we need to create associated class files. Recall that you could always use the artisan command to generate a base template code.

1
php artisan event:generate

That should have created the event class at app/Events/ClearCache.php and the listener class at app/Listeners/WarmUpCache.php.

With a few changes, the app/Events/ClearCache.php class should look like this:

1
<?php
2
3
namespace App\Events;
4
5
use Illuminate\Broadcasting\Channel;
6
use Illuminate\Broadcasting\InteractsWithSockets;
7
use Illuminate\Broadcasting\PresenceChannel;
8
use Illuminate\Broadcasting\PrivateChannel;
9
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
10
use Illuminate\Foundation\Events\Dispatchable;
11
use Illuminate\Queue\SerializesModels;
12
13
class ClearCache
14
{
15
    use Dispatchable, InteractsWithSockets, SerializesModels;
16
17
    public $cache_keys = [];
18
19
    /**

20
     * Create a new event instance.

21
     *

22
     * @return void

23
     */
24
    public function __construct(Array $cache_keys)
25
    {
26
        $this->cache_keys = $cache_keys;
27
    }
28
29
    /**

30
     * Get the channels the event should broadcast on.

31
     *

32
     * @return \Illuminate\Broadcasting\Channel|array

33
     */
34
    public function broadcastOn()
35
    {
36
        return new PrivateChannel('channel-name');
37
    }
38
}

As you've probably noticed, we've added a new property $cache_keys which will be used to hold the information which will be passed along with an event. In our case, we'll pass cache groups that were flushed.

Next, let's have a look at the listener class with an updated handle method at app/Listeners/WarmUpCache.php.

1
<?php
2
3
namespace App\Listeners;
4
5
use App\Events\ClearCache;
6
use Illuminate\Contracts\Queue\ShouldQueue;
7
use Illuminate\Queue\InteractsWithQueue;
8
9
class WarmUpCache
10
{
11
    /**

12
     * Create the event listener.

13
     *

14
     * @return void

15
     */
16
    public function __construct()
17
    {
18
        //

19
    }
20
21
    /**

22
     * Handle the event.

23
     *

24
     * @param  ClearCache  $event

25
     * @return void

26
     */
27
    public function handle(ClearCache $event)
28
    {
29
        if (isset($event->cache_keys) && count($event->cache_keys)) {
30
            foreach ($event->cache_keys as $cache_key) {
31
                // generate cache for this key

32
                // warm_up_cache($cache_key)

33
            }
34
        }
35
    }
36
}

When the listener is invoked, the handle method is passed with an instance of the associated event. In our case, it should be an instance of the ClearCache event class, which will be passed as the first argument to the handle method.

Next, it's just a matter of iterating through each cache key and warming up the associated caches.

Now, we have everything in place to test things against. Let's quickly create a controller file at app/Http/Controllers/EventController.php to demonstrate how you could raise an event.

1
<?php
2
namespace App\Http\Controllers;
3
4
use App\Http\Controllers\Controller;
5
use App\Library\Services\Contracts\CustomServiceInterface;
6
use App\Post;
7
use Illuminate\Support\Facades\Gate;
8
use App\Events\ClearCache;
9
10
class EventController extends Controller
11
{
12
    public function index()
13
    {
14
        // ...

15
         
16
        // you clear specific caches at this stage

17
        $arr_caches = ['categories', 'products'];
18
         
19
        // want to raise ClearCache event

20
        event(new ClearCache($arr_caches));
21
         
22
        // ...

23
    }
24
}

Firstly, we've passed an array of cache keys as the first argument while creating an instance of the ClearCache event.

The event helper function is used to raise an event from anywhere within an application. When the event is raised, Laravel calls all listeners listening to that particular event.

In our case, the App\Listeners\WarmUpCache listener is set to listen to the App\Events\ClearCache event. Thus, the handle method of the App\Listeners\WarmUpCache listener is invoked when the event is raised from a controller. The rest is to warm up caches that were cleared!

So that's how you can create custom events in your application and work with them.

What Is an Event Subscriber?

The event subscriber allows you to subscribe to multiple event listeners in a single place. Whether you want to logically group event listeners or you want to contain growing events in a single place, it's the event subscriber you're looking for.

If we had implemented the examples discussed so far in this article using the event subscriber, it might look like this.

1
<?php
2
// app/Listeners/ExampleEventSubscriber.php

3
namespace App\Listeners;
4
5
use Illuminate\Auth\Events\Login;
6
use App\Events\ClearCache;
7
8
class ExampleEventSubscriber
9
{
10
    /**

11
     * Handle user login events.

12
     */
13
    public function sendEmailNotification($event) {
14
        // get logged in username

15
        $email = $event->user->email;
16
        $username = $event->user->name;
17
         
18
        // send email notification about login...

19
    }
20
21
    /**

22
     * Handle user logout events.

23
     */
24
    public function warmUpCache($event) {
25
        if (isset($event->cache_keys) && count($event->cache_keys)) {
26
            foreach ($event->cache_keys as $cache_key) {
27
                // generate cache for this key

28
                // warm_up_cache($cache_key)

29
            }
30
        }
31
    }
32
33
    /**

34
     * Register the listeners for the subscriber.

35
     *

36
     * @param  Illuminate\Events\Dispatcher  $events

37
     */
38
    public function subscribe($events)
39
    {
40
        $events->listen(
41
            Login::class,
42
            [ExampleEventSubscriber::class, 'sendEmailNotification']
43
        );
44
         
45
        $events->listen(
46
            ClearCache::class,
47
            [ExampleEventSubscriber::class, 'warmUpCache']
48
        );
49
    }
50
}

It's the subscribe method which is responsible for registering listeners. The first argument of the subscribe method is an instance of the Illuminate\Events\Dispatcher class, which you could use to bind events with listeners using the listen method.

The first argument of the listen method is an event which you want to listen to, and the second argument is a listener which will be called when the event is raised.

In this way, you can define multiple events and listeners in the subscriber class itself.

The event subscriber class won't be picked up automatically. You need to register it in the EventServiceProvider.php class under the $subscribe property, as shown in the following snippet.

1
<?php
2
3
namespace App\Providers;
4
5
use Illuminate\Auth\Events\Registered;
6
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
7
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
8
use Illuminate\Support\Facades\Event;
9
use App\Listeners\WarmUpCache;
10
use App\Events\ClearCache;
11
use App\Listeners\ExampleEventSubscriber;
12
13
class EventServiceProvider extends ServiceProvider
14
{
15
    /**

16
     * The event listener mappings for the application.

17
     *

18
     * @var array

19
     */
20
    protected $listen = [        
21
    ];
22
23
    /**

24
     * The subscriber classes to register.

25
     *

26
     * @var array

27
     */
28
    protected $subscribe = [
29
        ExampleEventSubscriber::class,
30
    ];
31
32
    /**

33
     * Register any events for your application.

34
     *

35
     * @return void

36
     */
37
    public function boot()
38
    {
39
        parent::boot();
40
41
        //

42
    }
43
}

So that was the event subscriber class at your disposal, and with that we've reached the end of this article as well.

Conclusion

Today we've discussed a couple of exciting features of Laravel—events and listeners. They're based on the observer design pattern, which allows you to raise application-wide events and allow other modules to listen to those events and react accordingly.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.