Events in Laravel

What are Events in Laravel?

Events in Laravel allow for decoupled communication between different components of your application. By dispatching events when certain actions are done, you can define listeners to handle the responses. This makes your code more modular and maintainable.


Origin

Events have long been a key component of Laravel, aiming to simplify application operations by isolating business logic from triggering actions.


Why Are Events Used?

  1. Decouples Logic: Separates event triggers and response handling, which improves code readability.
  2. Improves Scalability: Multiple listeners can respond to the same event, allowing for more flexible application behaviors.
  3. Simplifies. Workflow: Offers a simple, systematic approach to managing and expanding program functionality.

Best Practices.

  1. Keep Listeners Focused: Assign each listener a single, clear job.
  2. Use Events for Reusable Logic: Trigger events for shared procedures like notice sending and activity logging.
  3. Use Queued Listeners: They run intensive tasks in the background. This improves app performance.

Example in Action

Create an event:

php artisan make:event OrderShipped

In the event class:

namespace App\Events;

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

class OrderShipped
{
    use Dispatchable;

    public $order;

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

Create a listener:

php artisan make:listener SendShipmentNotification

Register the event and listener in EventServiceProvider:

protected $listen = [
    OrderShipped::class => [
        SendShipmentNotification::class,
    ],
];

Dispatch the event:

OrderShipped::dispatch($order);

Read more