Observer Events in Laravel you may not know?

Tram Ho

1. Introduction

If you are and have used Laravel for a medium to large project, you may have come across a situation where you want to perform some action in the Eloquent model you are dealing with. Laravel Eloquent provides a convenient way to add your own actions while the model is completing or has completed some actions.

Suppose you have a series of actions that take place one after another and depend on each other for example: when you delete a post, you also want to delete all its comments, or when you register successfully an account will automatically send emails to subscribers, … Although you can write the whole logic of that code in the Controller. But today I would like to introduce to you about Observer Events . First we will learn about Eloquent Model Events offline!

2. Laravel Model Events

Eloquent has provided events for you to hook at some point in its life cycle:

  • 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.

3. Laravel Model Observers

As the example above, suppose you want to delete 1 post and delete all the comments of that post. Although we can handle it in the main PostController, but so it looks quite confusing code, right? Thankfully, Laravel has provided us with Observer Events, which can hook at different times during a post’s life cycle.

3.2 Create observer

You can easily create observer by running the command:

In this example, I will create 1 PostObserver

The PostObserver.php file will be created in the app / Observers directory and will have the following structure:

3.2 Register observer

To use it, you must register it in the boot () function of AppServiceProvider

3.3 Example

I will take the VD when I delete a post, I will delete all comments of that post, here I will use the deleting function to hook that event. Here I use HasMany relationship

Now I can add a deleting hook in PostObserver to delete all the comments of that post.

So you’ve successfully deleted all those comments ?

To understand more, please refer to here

Share the news now

Source : Viblo