Member-only story

A Step-by-Step Guide to Laravel Events and Listeners with Examples

ArjunAmrutiya
3 min readJul 25, 2023

--

Introduction:
Laravel, a popular PHP framework, offers a robust event system that allows developers to implement a clean and efficient way to manage application events and their corresponding actions. Events and listeners in Laravel facilitate the decoupling of components, making your codebase more maintainable and scalable. In this step-by-step guide, we will walk you through the process of using Laravel Events and Listeners with practical examples.

Step 1: Setting Up a Laravel Project Assuming you already have Laravel installed on your system, create a new Laravel project using Composer by running the following command in your terminal:

composer create-project --prefer-dist laravel/laravel laravel-event-example

Step 2: Create an Event Laravel provides a simple command to generate events. Run the following command in your terminal:

php artisan make:event OrderPlaced

This will generate an event class named OrderPlaced in the app/Events directory. Open this file to see the structure of the event.

Step 3: Define Event Properties and Constructor Within the OrderPlaced event class, you can define any properties that you want to pass to the listener. For instance, if you want to pass the order details, you can define a public property like this:

public $order;

public function __construct(Order $order)
{
$this->order = $order;
}

Step 4: Create a Listener Next, let’s generate a listener for our event. Run the following command:

php artisan make:listener SendOrderConfirmation --event=OrderPlaced

This command will create a listener class named SendOrderConfirmation in the app/Listeners directory. Open this file to see the structure of the listener.

Step 5: Implement the Listener Logic Within the SendOrderConfirmation listener class, you can implement the logic that should be executed when the OrderPlaced event is fired. For example, let's send an email confirmation to the customer:

use App\Mail\OrderConfirmation;
use Illuminate\Support\Facades\Mail;

public function handle(OrderPlaced $event)
{
$order =…

--

--

ArjunAmrutiya
ArjunAmrutiya

Written by ArjunAmrutiya

👋 Hey there! I'm Arjun Amrutiya, a passionate web developer and blogger who loves all things PHP, Laravel and Vue.js. Welcome to my Medium account!

Responses (2)