Laravel 11 for Beginners: Events and Listeners

Arlind Musliu Portrait
Arlind Musliu

January 10, 2024 · 4 min read · 80 views

Laravel Blogpost Image

2024 UPDATE - LARAVEL 11

We're excited to announce that we have updated all of our blog post examples to reflect the new Laravel 11 version! Our previous examples were based on Laravel 10, but with the release of Laravel 11, we wanted to ensure that our readers have access to the most up-to-date information and examples.

Automating Actions in Your App

When building an application with Laravel, you'll want to create a dynamic and responsive experience for your users. That's where Laravel's event system comes into play. Events in Laravel are a way of decoupling various parts of your application and allowing them to communicate with each other through dispatched events and their listeners.

Understanding Events and Listeners

Think of events as announcements broadcast throughout your application, signaling that something significant has happened. For instance, a new blog post has been published, or a user has registered.

Listeners are like the attentive audience, waiting for specific events to occur. When an event is dispatched, all its listeners are triggered, and they execute the code meant to respond to that event.

Creating Events

In Laravel, you can create an event using the command:

php artisan make:event PostPublished

This command will generate a new event class in the app/Events directory. Here's a basic example of what the PostPublished event class could look like:

<?php

namespace App\Events;

use Illuminate\Foundation\Events\Dispatchable;
use App\Models\Post;

class PostPublished
{
    use Dispatchable;

    public $post;

    public function __construct(Post $post)
    {
        $this->post = $post;
    }
}

The PostPublished event class contains a public property $post, which represents the blog post that has been published. The __construct method sets this property when the event is created.

Creating Listeners

Listeners are responsible for handling the actions that should occur when an event is dispatched. You can create a listener with the following Artisan command:

php artisan make:listener SendPostPublishedNotification --event=PostPublished

This command creates a listener class and associates it with the PostPublished event. The listener would be placed in the app/Listeners directory. Here's an example of what the listener might look like:

<?php

namespace App\Listeners;

use App\Events\PostPublished;
use Illuminate\Support\Facades\Mail;
use App\Mail\PostPublished as PostPublishedMail;

class SendPostPublishedNotification
{
    public function handle(PostPublished $event)
    {
        // Send an email notification about the published post
        Mail::to($event->post->author->email)
				->send(new PostPublishedMail($event->post));
    }
}

In this listener, the handle method is where you define the actions to take when the event is triggered. In our case, it's sending an email to the author of the post.

This code will not work before you configure the mailable in a different post. No worries, once we get there you will understand how to use the events and listeners in a real situation.

Registering Events and Listeners

By default, Laravel will automatically find and register your event listeners by scanning your application's Listeners directory. When Laravel finds any listener class method that begins with handle or __invoke, Laravel will register those methods as event listeners for the event that is type-hinted in the method's signature:

<?php

namespace App\Listeners;

use App\Events\PostPublished;
use Illuminate\Support\Facades\Mail;

class SendPostPublishedNotification
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(PostPublished $event): void
    {
        Mail::to($event->post->author->email)
            ->send(new PostPublished($event->post));
    }
}

If you plan to store your listeners in a different directory or within multiple directories, you may instruct Laravel to scan those directories using the withEvents method in your application's bootstrap/app.php file:

->withEvents(discover: [

__DIR__.'/../app/Domain/Listeners',

])

The event:list command may be used to list all of the listeners registered within your application:

php artisan event:list

Manually Registering Events

Using the Event facade, you may manually register events and their corresponding listeners within the boot method of your application's AppServiceProvider:

<?php

namespace App\Providers;

use App\Events\PostPublished;
use App\Listeners\SendPostPublishedNotification;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Event::listen(
            PostPublished::class,
            SendPostPublishedNotification::class,
        );
    }
}


Dispatching Events

With your events and listeners set up and registered, you can dispatch an event from anywhere in your application. Here's how you might dispatch the PostPublished event in the PostController after a new post is created:

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use App\Models\Tag;
use Illuminate\Http\Request;

class PostController extends Controller
{
    // Other methods

    // Store a newly created blog post
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'title' => 'required|max:255',
            'content' => 'required',
            // other validation rules...
        ]);

		// the new post belongs to the authenticated user
        $post = auth()->user()->posts()->create($validatedData);

		 // Dispatch the event
		 PostPublished::dispatch($post);

        return redirect()->route('posts.show', $post);
    }

        // Other methods
}

This code snippet can also be placed in a service provider, depending on where you want to handle the post creation logic.

Conclusion

Events and listeners in Laravel provide a clean and expressive way to handle actions in response to various operations within your application. With this system, your blog can automatically notify users, clear caches, log activities, and more, all while keeping your code organized and your components loosely coupled.

Upcoming Articles in the Series

  1. Laravel for Beginners: Collections for Data Handling

  2. Laravel for Beginners: PHPUnit and PEST Tests

  3. Laravel for Beginners: Blade and Breeze


Bring Your Ideas to Life 🚀

If you need help with a Laravel project let's get in touch.

Lucky Media is proud to be recognized as a Top Laravel Development Agency

Arlind Musliu Portrait
Arlind Musliu

Cofounder and CFO of Lucky Media

Technologies:

Laravel
Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!