How to use Laravel Model Observers

7 months ago admin Laravel

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();
        }
    }
}

Related Tuorials

How to Check if a Record Does Not Exist in Laravel

in this lesson, we will see how to check if a record does not exist in laravel, sometimes you need t...


How to Check if a Record Exists in Laravel

in this lesson, we will see how to check if a record exists in laravel, sometimes you need to check...


How to Decrement Multiple Fields in Laravel

In this lesson, we will see how to decrement multiple fields in Laravel, in the old versions of lara...


How to Increment Multiple Fields in Laravel

In this lesson, we will see how to increment multiple fields in Laravel, in the old versions of lara...


How to Use the Same Request Validation Rules for Storing and Updating in Laravel

In this lesson, we will see how to use the same request validation rules for storing and updating in...


How to Go Back to the Previous URL in Laravel Blade

In this lesson, we will see how to go back to the previous URL in Laravel Blade, sometimes we need t...


How to Add Additional Data to The Resource JSON Response in Laravel

In this lesson, we will see how to add additional data to the resource JSON response in Laravel, let...


How to Specify the Attributes to be Returned in the Laravel Find Method

In this lesson, we will see how to specify the attributes to be returned in the Laravel find method,...


How to Get Data Using Where All in Laravel

In this lesson, we will see how to get data using Where All in Laravel, the Where All method is used...


How to Get Data Using Where Any in Laravel

In this lesson, we will see how to get data using Where Any in Laravel, the Where Any method is used...