Events let your app react to things happening, like a user logging in. They help keep your code organized and easy to manage.
Defining events in Laravel
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Laravel
php artisan make:event EventName // Event class example namespace App\Events; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class EventName { use Dispatchable, SerializesModels; public $data; public function __construct($data) { $this->data = $data; } }
Use php artisan make:event EventName to create a new event class.
Events usually carry data that listeners can use.
Examples
UserRegistered.Laravel
php artisan make:event UserRegistered
$user object to share with listeners.Laravel
namespace App\Events;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class UserRegistered
{
use Dispatchable, SerializesModels;
public $user;
public function __construct($user)
{
$this->user = $user;
}
}Sample Program
This example defines an OrderPlaced event that carries an order ID. When an order is placed, the event is fired with the order ID.
Laravel
<?php namespace App\Events; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class OrderPlaced { use Dispatchable, SerializesModels; public $orderId; public function __construct(int $orderId) { $this->orderId = $orderId; } } // Usage example in a controller or service use App\Events\OrderPlaced; function placeOrder(int $orderId) { // Order placing logic here event(new OrderPlaced($orderId)); return "Order placed with ID: $orderId"; } // Calling the function echo placeOrder(123);
Important Notes
Events help keep your code clean by separating actions from reactions.
Always pass only the data listeners need to the event.
Use Laravel's event() helper to fire events easily.
Summary
Events are special classes that represent something happening in your app.
You create events with artisan and add data to share.
Fire events to let other parts of your app respond.
Practice
1. What is the main purpose of defining events in a Laravel application?
easy
Solution
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.Step 2: Compare with other options
Modifying database tables, creating UI components, and handling routing are done by other parts of Laravel, not events.Final Answer:
To respond to actions in a clean and organized way -> Option AQuick 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
Solution
Step 1: Recall the artisan command for events
The correct command to create an event isphp artisan make:event EventName.Step 2: Check each option
Only php artisan make:event UserRegistered matches the correct syntax. Others use invalid commands or flags.Final Answer:
php artisan make:event UserRegistered -> Option AQuick 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:
What will be the correct way to fire this event with an
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
Solution
Step 1: Understand how to fire events in Laravel
Events are fired by calling the globalevent()helper with a new instance of the event class.Step 2: Check each option
event(new OrderShipped($order)); correctly usesevent(new OrderShipped($order)). event(OrderShipped($order)); missesnew, C and D use invalid syntax.Final Answer:
event(new OrderShipped($order)); -> Option CQuick 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
Solution
Step 1: Check constructor syntax in PHP
In modern PHP (and Laravel), constructors must be named__construct, not the class name.Step 2: Verify other options
Property visibility is correct as public, extending base class is optional, so only constructor name is wrong.Final Answer:
Constructor method name should be __construct, not class name -> Option DQuick 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
Solution
Step 1: Check constructor naming and parameter types
The constructor must be named__constructand accept typed parameters for clarity and safety.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.Final Answer:
public function __construct(Invoice $invoice, float $amount) { $this->invoice = $invoice; $this->amount = $amount; } -> Option BQuick 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
