# Observers in Laravel

What are Observers in Laravel?

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.

---

## Origin

Observers are part of [Laravel's event system](https://sorane.io/glossary/events-in-laravel), which is designed to provide a consistent and efficient way to manage model-related events.

---

## Why are Observers Used?

1. **Centralizes Logic**: Combines all event-handling logic for a model into a single observer class.
2. **Promotes Code Reusability**: The same observer can be used across numerous models, minimizing redundancy.
3. **Improves maintainability**: Event-related duties are offloaded, keeping models and controllers tidy.

---

## Best Practices.

1. **Limit Observer Responsibilities**: To avoid overcomplication, assign each observer to handle only event-specific tasks.
2. **Thoroughly test the observers**: Write tests to check that all expected event-handling behaviors execute properly.
3. **Avoid Using Heavy Logic in Observers**: For complex tasks, delegate them to jobs, services, or other specific classes.

---

## Example in Action

Create an observer:

```bash
php artisan make:observer UserObserver --model=User
```

In the observer class:

```php
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:

```php
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.
```php
use App\Observers\UserObserver;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
 
#[ObservedBy([UserObserver::class])]
class User extends Authenticatable
{
    //
}
```

Read this definition in a browser: https://ranetrace.com/glossary/observers-in-laravel
