The Laravel Event System provides a way to decouple various parts of your application by allowing components to communicate using events. Events can be dispatched when specific actions occur, and listeners handle the response logic.
The Event System has been a part of Laravel to facilitate a clean way of handling application workflows by decoupling business logic.
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);
The Laravel Event System simplifies communication within your application, improving modularity and scalability.