How to use Laravel Model Observers
In this lesson, we will see how to use Laravel model observers, a Laravel model observer is used to listen to an event for a given model for example: create, update, or delete.
Create observers
First, let's assume that we have a commenting system in our application and we want before a comment is created to add the user_id automatically using a model observer.
So let's create the observer:
php artisan make:observer CommentObserver --model=Comment
Register an observer
Next, we register the observer inside the boot method of our application's service provider 'App\Providers\AppServiceProvider'.
<?php
namespace App\Providers;
use App\Models\Comment;
use App\Observers\CommentObserver;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
Comment::observe(CommentObserver::class);
}
}
Adding the user id
To add the user_id before a comment is created using the model observer let's use the code below:
<?php
namespace App\Observers;
use App\Models\Comment;
class CommentObserver
{
/**
* Handle the comment "creating" event.
*/
public function creating(Comment $comment)
{
if (auth()->check()) {
$comment->user_id = auth()->id();
}
}
}