Use Model Observers in Laravel

Tram Ho

Introducing Laravel Model Events

If you have used Laravel for medium and large scale projects, you may have come across a situation where you want to take some action while Eloquent is processing. You can do it manually but you don’t know that Laravel Eloquent provides a simple way to add in the model while the model is completing or has completed some actions. ?? For example, you have a model called Post and you want it to automatically add slug from the title while you are performing the operation to add a new post. You can do this by setting your model when a new post is added with a saving event like this ?? :

Eloquent provides the following events when we manipulate the model:

  • retrieved: after a record has been retrieved from the database.
  • creating: before a record has been created
  • created: after a record has been created
  • updating: before a record is updated.
  • updated: after a record has been updated.
  • saving: before a record is saved (created or updated)
  • saved: after the record has been saved (created or updated).
  • deleting: before a record is deleted or soft deleted.
  • deleted: after a record has been deleted or soft deleted.
  • restoring: before the softly deleted record will be restored.
  • restored: after the soft deleted record has been restored.

Laravel Model Observers

Imagine that your application grows and grows day by day you will be very tired or have to handle a lot after each manipulation of the model. ??? But if you use Observer then everything will be very simple ?? . Using model observers, you can group all your events into one class. All method names in the observer class will automatically reflect on each of the events listed above. You can create an observer model class using php artisan like this:

The above command will create a new class in the project directory like this app/Observers :

Now you need to add the newly created class above to the AppServiceProvider file in the boot() to tell the Post model that every time any event (as I have listed above) affects the Post model, Let’s implement the methods defined in observe as PostObserver like this ?? :

Then as mentioned above we want to add the slug every time we create a new post, we will do it with the on saving method as follows:

Now every time you create a new post it will automatically get the title converted to slug and add it to the attribute slug very well, right? ???

Conclude

Above is an article on how to use observer with model, in fact, when we code a large project, when using observer, it is actually a very optimal and very good time-saving way. you succeed ??

References

Share the news now

Source : Viblo