Observers Laravel help remove cleanup code from controllers that must be executed before and after model events. They also provide the ability to connect to the lifecycle of model events and execute logic at their discretion.

Observers Laravel are used when you want a template to wait for multiple events to happen simultaneously. Observers only need to be registered once rather than every time an event is created.

Laravel Observers, as the name suggests, are used to observe applications. Creating an observer has many uses. For example, if you want to modify a template instance when you create it or update, delete, or restore a template instance, you don’t need to call the event separately or write code in the controller each time. All you need for an observer that performs the necessary actions in the background.

Laravel Observer’s Eloquent

Observable model events span model CRUD, including

  • search
  • create.
  • Create.
  • Update from
  • Update from
  • save
  • save
  • deleted
  • deleted
  • recover
  • recover

The above events can be observed in the Laravel framework for each Model and its associated business logic. Other parts can also hear them of the application by sending custom observer events.

Example.

In this example, we’ll look at a food model with columns for name, bag, price, and unique ID. So we need to create a record with only the name and price. However, we need to generate the slug from the name and automatically generate a unique ID on creation.

Laravel watchers can help you fire multiple events and do CRUD operations on the database.

app/Models/Food.php

  

namespace AppModels;

  

use IlluminateDatabaseEloquentFactoriesHasFactory;

use IlluminateDatabaseEloquentModel;

  

class Food extends Model

{

    use HasFactory;

  

    protected $fillable = [

        ‘name’, ‘price’, ‘slug’, ‘unique_id’

    ];

}

For example, when the user creates a level and reaches a certain level, the observer will fire the corresponding method (event) and do what you wrote. Creating an observer allows you to listen for certain conditions in your Model.

Real-world examples

In the world of websites, there are many things you want to do when a user registers on your website! For example, sending emails, sending text messages, etc. So why not leave it to the audience?

First, create a user watcher (for the user model) by running the following command.

php artisan make:observer UserObserver –model=User

Next, four of these methods come into play when conditions are met. These methods are.

namespace AppObservers;

use AppModelsUser;

class UserObserver

{

    /**

     * Will do what you wanted When an instance of the Model created 

     *

     * @param AppModelsUser $user

     * @return void

     */

    public function created(User $user)

    {

        //

    } 

    /**

     * Will do what you want When an instance of the Model updated

     *

     * @param AppModelsUser $user

     * @return void

     */

    public function updated(User $user)

    {

        //

    }

    /**

     * Will do what you wanted When an instance of Model deleted

     *

     * @param AppModelsUser $user

     * @return void

     */

    public function deleted(User $user)

    {

        //

    }

    /**

     * Will do what you want When an instance of model force deleted

     *

     * @param AppModelsUser $user

     * @return void

     */

    public function forceDeleted(User $user)

    {

        //

    }

}

Benefits of observer Laravel

The Control Unit is Tilted

Observers allow controllers to do what they are supposed to do. Receive a request and return a response. Using observers, more logic can be passed to the model layer, which is now considered best practice.

Promote Maintainable Code

Observers make it easier to stick to the “simple and foolproof” principle. By abstracting parts of the logic into observers, the codebase can be organized, and design patterns can be defined to make it easier for future developers working on the codebase to understand.

Promote Reusable Code

The first example below shows that observers make the codebase very DRY (don’t repeat yourself). By avoiding repetition, errors can be minimized and localized. Don’t you want to fix the same bug here and there? Or only in one place? It is a matter of course.

Limitation

Some further limitations should be noted when using model observers. If you use memory hooks, you must not call the Model’s memory methods if you want to use memory hooks to call memory methods. If your logic requires you to call a model memory method, please review your logic or do not use observers Laravel.

Conclusion

Eloquent Model Watchers are a powerful and useful feature but should be used cautiously. They make the codebase more manageable, but you should also be aware of their limitations. To get best quotes for  your project contact us.