A Laravel Observer is a class that allows you to listen to and handle events that occur on a model, such as creating, updating, or deleting. Observers centralize logic for handling these events, promoting cleaner and more maintainable code.
Observers are part of Laravel's event system and were introduced to provide a structured way to handle model-related events.
Create an observer:
php artisan make:observer UserObserver --model=User
In the observer class:
namespace App\Observers;
use App\Models\User;
class UserObserver
{
public function creating(User $user)
{
$user->uuid = Str::uuid();
}
}
Register the observer in a service provider:
use App\Models\User;
use App\Observers\UserObserver;
User::observe(UserObserver::class);
Laravel Observers streamline event handling for models, improving code organization and maintainability.