The Observer Pattern in Laravel is implemented using Model Observers. Observers allow you to listen to and handle model events, such as created
, updated
, or deleted
, to encapsulate logic that would otherwise clutter your controllers or models.
The Observer Pattern is a common design pattern used in software development to define relationships between objects and notify dependents of changes. Laravel integrates it seamlessly into Eloquent models.
Create an observer for the User
model:
php artisan make:observer UserObserver --model=User
In the generated UserObserver
class:
namespace App\Observers;
use App\Models\User;
class UserObserver
{
public function created(User $user)
{
// Logic to execute when a user is created
Log::info("User created: {$user->email}");
}
}
Register the observer in a service provider:
use App\Models\User;
use App\Observers\UserObserver;
public function boot()
{
User::observe(UserObserver::class);
}
Now, whenever a User
is created, the observer will handle the event.