How does Laravel Observer pattern work?
Posted: August 13, 2024 • 3 min read 526 word count
By: Ormel Flores
laravelphpIn Laravel, Observers are used to handle events related to Eloquent models. These events include actions like creating, updating, deleting, and restoring records. Observers provide a clean and organized way to manage these events by encapsulating the logic in separate classes, promoting the Single Responsibility Principle.
Why Use Observers?
Observers offer several benefits:
- Separation of Concerns: By moving event-handling logic out of your models and controllers, Observers help keep your codebase clean and maintainable.
- Reusability: You can reuse the same Observer class for different models, making it easier to manage common logic.
- Ease of Testing: Isolated event-handling logic in Observers can be tested independently from your models and controllers.
How to Create and Use Observers in Laravel
Step 1: Generate an Observer
You can create an Observer using the Artisan command-line tool. For example, to create an observer for a User
model, run:
php artisan make:observer UserObserver --model=User
This command generates a new UserObserver
class in the app/Observers
directory and automatically binds it to the User
model.
Step 2: Define Observer Methods
Open the generated UserObserver
class located at app/Observers/UserObserver.php. You'll find stub methods for common model events. You can define your custom logic in these methods:
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->title);
}
public function updated(User $user)
{
// Logic to execute when a user is updated
\Log::info('User updated: '.$user->title);
}
public function deleted(User $user)
{
// Logic to execute when a User is deleted
\Log::info('User deleted: '.$user->title);
}
// Additional methods for other events like restored, forceDeleted, etc.
}
Step 3: Register the Observer
If you are using the laravel 10 or the latest version, you will need to register the observer in the App/Models/User
. Open the User.php
file and add the following code:
use App\Observers\UserObserver;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
#[ObservedBy([UserObserver::class])]
class User extends Authenticatable
{
//
}
If you are using below laravel 10 version, you will need to register the observer in the AppServiceProvider
or any other service provider of your choice. Open app/Providers/AppServiceProvider.php
and add the following code to the boot method:
use App\Models\User;
use App\Observers\UserObserver;
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
User::observe(UserObserver::class);
}
This tells Laravel to use the UserObserver
class for observing events on the User
model.
Step 4: Test Your Observer
To test your observer, create, update, or delete a User
record. Check your log files (storage/logs/laravel.log
) to see if the Observer methods are being triggered as expected.
Advanced Usage
Observers can be extended with more complex logic, such as dispatching jobs, sending notifications, or integrating with external services. Here are a few examples:
- Dispatching Jobs:
use App\Jobs\SendUserNotification;
public function created(User $user)
{
SendUserNotification::dispatch($user);
}
- Sending Notifications
use App\Notifications\UserCreatedNotification;
public function created(User $user)
{
$user->notify(new UserCreatedNotification($user));
}
- Integrating with External Services:
public function updated(User $user)
{
// Example of sending data to an external API
Http::post('https://api.example.com/notify', [
'email' => $user->email,
'status' => $user->status,
]);
}
Conclusion
Laravel Observers are a powerful feature that helps you manage and respond to Eloquent model events efficiently. By using Observers, you can keep your code organized, promote reusability, and enhance maintainability. Whether you're handling simple logging or complex business logic, Observers provide a clean and effective way to manage model events.
Start integrating Observers into your Laravel applications to leverage their benefits and improve your codebase. Happy coding!
This post is licensed under CC BY 4.0 by the author.