Bird
Raised Fist0
Laravelframework~10 mins

Defining events in Laravel - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Defining events
Create Event Class
↓
Define Event Properties
↓
Create Listener Class
↓
Register Event and Listener
↓
Fire Event in Code
↓
Listener Handles Event
This flow shows how you create an event class, define its data, create a listener, register both, then fire the event so the listener reacts.
Execution Sample
Laravel
php artisan make:event OrderShipped

class OrderShipped {
  public $order;
  public function __construct($order) {
    $this->order = $order;
  }
}
This code creates an event class named OrderShipped that holds an order object passed when the event is fired.
Execution Table
StepActionCode/CommandResult/State Change
1Create event classphp artisan make:event OrderShippedOrderShipped.php file created with class skeleton
2Add property and constructorpublic $order; public function __construct($order) { $this->order = $order; }Event class now holds order data
3Create listener classphp artisan make:listener SendShipmentNotificationListener class created to handle event
4Register event and listenerIn EventServiceProvider.php, add to $listen arrayLaravel knows which listener to call for OrderShipped
5Fire event in codeevent(new OrderShipped($order));Event dispatched, listeners triggered
6Listener handles eventpublic function handle(OrderShipped $event) { // send notification }Notification sent using event data
7ExitNo more listenersEvent handling complete
💡 All listeners for the event have run, so event processing stops.
Variable Tracker
VariableStartAfter Step 2After Step 5Final
$ordernullpassed to constructorpassed to event instanceused in listener to send notification
OrderShipped instancenonecreated with $orderdispatched via event()passed to listener handle()
Key Moments - 3 Insights
Why do we need to define properties and a constructor in the event class?
Because the event needs to carry data (like $order) to listeners. Step 2 shows adding these so listeners can access event info.
How does Laravel know which listener to run for an event?
In Step 4, the event and listener are registered in EventServiceProvider.php. This mapping tells Laravel which listener handles which event.
What happens when we call event(new OrderShipped($order))?
Step 5 shows firing the event. Laravel dispatches it and calls all registered listeners, as seen in Step 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is created at Step 1?
AAn event class file named OrderShipped.php
BA listener class file named SendShipmentNotification.php
CThe EventServiceProvider.php file
DThe notification email
💡 Hint
Check Step 1 in the execution_table where the event class is created.
At which step is the event fired so listeners start working?
AStep 3
BStep 5
CStep 2
DStep 6
💡 Hint
Look at Step 5 in execution_table where event(new OrderShipped($order)) is called.
If we forget to register the listener in EventServiceProvider, what happens?
AThe listener still runs automatically
BThe event class won't be created
CThe listener won't run when the event fires
DThe event won't fire at all
💡 Hint
Refer to Step 4 where registration links event and listener.
Concept Snapshot
Defining events in Laravel:
1. Create event class with php artisan make:event.
2. Add properties and constructor to pass data.
3. Create listener class.
4. Register event-listener in EventServiceProvider.
5. Fire event with event(new EventName(data));
6. Listener handles event data.
Full Transcript
In Laravel, defining events starts by creating an event class using artisan. This class holds any data you want to pass to listeners, like an order object. Next, you create a listener class that will respond when the event fires. You must register the event and listener in the EventServiceProvider so Laravel knows which listener to call. When you fire the event in your code using event(new EventName(data)), Laravel dispatches it and calls all registered listeners. The listener then handles the event, for example sending a notification. This process helps separate concerns and makes your app more organized.

Practice

(1/5)
1. What is the main purpose of defining events in a Laravel application?
easy
A. To respond to actions in a clean and organized way
B. To directly modify database tables
C. To create user interface components
D. To handle HTTP routing

Solution

  1. Step 1: Understand the role of events

    Events in Laravel are designed to help the app respond to actions or changes without mixing code logic.
  2. Step 2: Compare with other options

    Modifying database tables, creating UI components, and handling routing are done by other parts of Laravel, not events.
  3. Final Answer:

    To respond to actions in a clean and organized way -> Option A
  4. Quick Check:

    Events = Respond to actions [OK]
Hint: Events handle actions, not UI or database directly [OK]
Common Mistakes:
  • Confusing events with database migrations
  • Thinking events create UI elements
  • Mixing events with routing logic
2. Which artisan command correctly creates a new event named UserRegistered?
easy
A. php artisan make:event UserRegistered
B. php artisan event:create UserRegistered
C. php artisan make:event --new UserRegistered
D. php artisan create:event UserRegistered

Solution

  1. Step 1: Recall the artisan command for events

    The correct command to create an event is php artisan make:event EventName.
  2. Step 2: Check each option

    Only php artisan make:event UserRegistered matches the correct syntax. Others use invalid commands or flags.
  3. Final Answer:

    php artisan make:event UserRegistered -> Option A
  4. Quick Check:

    make:event = create event [OK]
Hint: Use 'make:event' with artisan to create events [OK]
Common Mistakes:
  • Using 'event:create' instead of 'make:event'
  • Adding unnecessary flags like '--new'
  • Swapping command order
3. Given this event class snippet:
class OrderShipped {
    public $order;
    public function __construct($order) {
        $this->order = $order;
    }
}

What will be the correct way to fire this event with an $order object?
medium
A. event(OrderShipped($order));
B. OrderShipped::fire($order);
C. event(new OrderShipped($order));
D. fire_event('OrderShipped', $order);

Solution

  1. Step 1: Understand how to fire events in Laravel

    Events are fired by calling the global event() helper with a new instance of the event class.
  2. Step 2: Check each option

    event(new OrderShipped($order)); correctly uses event(new OrderShipped($order)). event(OrderShipped($order)); misses new, C and D use invalid syntax.
  3. Final Answer:

    event(new OrderShipped($order)); -> Option C
  4. Quick Check:

    Fire event = event(new EventClass) [OK]
Hint: Always use 'new' keyword inside event() to fire events [OK]
Common Mistakes:
  • Omitting 'new' keyword when firing event
  • Trying to call static fire methods
  • Using non-existent helper functions
4. Identify the error in this event class definition:
class ProductCreated {
    public $product;
    public function ProductCreated($product) {
        $this->product = $product;
    }
}
medium
A. Property should be private, not public
B. Missing public keyword before property
C. Event class must extend a base Event class
D. Constructor method name should be __construct, not class name

Solution

  1. Step 1: Check constructor syntax in PHP

    In modern PHP (and Laravel), constructors must be named __construct, not the class name.
  2. Step 2: Verify other options

    Property visibility is correct as public, extending base class is optional, so only constructor name is wrong.
  3. Final Answer:

    Constructor method name should be __construct, not class name -> Option D
  4. Quick Check:

    Constructor = __construct method [OK]
Hint: Use __construct() for constructors, not class name [OK]
Common Mistakes:
  • Using old PHP constructor style
  • Forgetting visibility keywords
  • Assuming event classes must extend a base class
5. You want to define an event InvoicePaid that carries an Invoice object and a payment amount. Which is the best way to define its constructor?
hard
A. public function __construct(array $data) { $this->invoice = $data['invoice']; $this->amount = $data['amount']; }
B. public function __construct(Invoice $invoice, float $amount) { $this->invoice = $invoice; $this->amount = $amount; }
C. public function InvoicePaid(Invoice $invoice, float $amount) { $this->invoice = $invoice; $this->amount = $amount; }
D. public function __construct($invoice, $amount) { $invoice = $invoice; $amount = $amount; }

Solution

  1. Step 1: Check constructor naming and parameter types

    The constructor must be named __construct and accept typed parameters for clarity and safety.
  2. Step 2: Verify property assignments

    public function __construct(Invoice $invoice, float $amount) { $this->invoice = $invoice; $this->amount = $amount; } correctly assigns parameters to properties. public function __construct($invoice, $amount) { $invoice = $invoice; $amount = $amount; } assigns parameters to themselves (wrong). public function InvoicePaid(Invoice $invoice, float $amount) { $this->invoice = $invoice; $this->amount = $amount; } uses old constructor name. public function __construct(array $data) { $this->invoice = $data['invoice']; $this->amount = $data['amount']; } uses array but less clear and no type safety.
  3. Final Answer:

    public function __construct(Invoice $invoice, float $amount) { $this->invoice = $invoice; $this->amount = $amount; } -> Option B
  4. Quick Check:

    Use __construct with typed params and assign to properties [OK]
Hint: Use __construct with typed params and assign to $this->props [OK]
Common Mistakes:
  • Using old constructor method name
  • Assigning parameters to themselves
  • Using untyped or array parameters without clarity