What is an Observer in Laravel?

Tommy
Written by Tommy

Posted On: Jan 11, 2019

 

    1 Answer Written

  •  Tommy
    Posted by Roman Lopez

    An observer attaches to an Eloquent Model for Laravel.

    This observer can listen to many different events that happen on the model such as: creating, created, saving, saved, deleting, deleted and many more... All of which you can find here:

    https://laravel.com/docs/5.8/eloquent#events

    The observer listens for these events and fires whenever said action is triggered, letting you preform pre or post procedure statements whenever an action is taken.

     For instance, if you have a user registration page, and every time you create a user, you want to ensure that the password is hashed... You can hook into the User "creating" event.

     public function creating(User $user) {
      $user->password = bcrypt($user->password);

    }

     This will ensure that every time a user is created with a password, that password is automatically hashed.

     In order to register the Observer, you should place it in either the boot() section of your AppServiceProvider or your own custom provider. Note: if you use a custom provider, be sure to register it in config/app.php

    You will need the model and the observer. IE:

     

    boot() {
       User::observe(new UserObserver);
    }

    // That's it...

     

    Now any events that the User model fires will be performed by the User Observer if you have identified any in the observer.

Please Login or Register to leave a response.

Related Questions