In Laravel, observers are classes that allow you to listen for and respond to model events like created, updated, and deleted. Centralizing this logic creates simpler, more maintainable code. It also helps coordinate event-related actions in an organized way.
Observers are part of Laravel's event system, which is designed to provide a consistent and efficient way to manage 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 the boot method of a service provider:
use App\Models\User;
use App\Observers\UserObserver;
public function boot(): void
{
User::observe(UserObserver::class);
}
Alternatively, you can use the ObservedBy
attribute on your Eloquent model.
use App\Observers\UserObserver;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
#[ObservedBy([UserObserver::class])]
class User extends Authenticatable
{
//
}