Laravel for Beginners: Events and Listeners

Arlind Musliu Portrait

Arlind Musliu

January 10, 2024 · 3 min read · 23 views

Laravel Blogpost Image

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

To hook up events with their listeners, you'll need to register them in the EventServiceProvider class, which is located in the app/Providers directory:

<?php

namespace App\Providers;

use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event to listener mappings for the application.
     *
     * @var array<class-string, array<int, class-string>>
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
		'App\Events\PostPublished' => [
			'App\Listeners\SendPostPublishedNotification',
		],
    ];

    /**
     * Register any events for your application.
     */
    public function boot(): void
    {
        //
    }

    /**
     * Determine if events and listeners should be automatically discovered.
     */
    public function shouldDiscoverEvents(): bool
    {
        return false;
    }
}

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
        event(new PostPublished($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:

Heading Pattern

Related Posts

Stay up to date

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