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.
Events have long been a key component of Laravel, aiming to simplify application operations by isolating business logic from triggering actions.
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);