Hi Guys, in this tutorial, we’ll learn about model events in Laravel for using them in our application.

Laravel Model events allow you to tap into various points in a model’s lifecycle, and can even prevent a save or delete from happening. The Laravel model events documentation outlines how you can hook into these events with event classes.

The model has the following events at the time of writing:

  • creating: Call Before Create Record.
  • created: Call After Created Record.
  • updating: Call Before Update Record.
  • updated: Class After Updated Record.
  • deleting: Call Before Delete Record.
  • deleted: Call After Deleted Record.
  • retrieved: Call Retrieve Data from Database.
  • saving: Call Before Creating or Updating Record.
  • saved: Call After Created or Updated Record.
  • restoring: Call Before Restore Record.
  • restored: Call After Restore Record.
  • replicating: Call on replicate Record.

According to the official website:

Example:

 

Read Also  How To Log All SQL Queries In Laravel

We simply added a static boot() method to our Post model. Inside this method, we called several methods and we passed a closure function that receives the instance of the Post model.

Inside the methods listener function, we can do all whatever we want, for example in creating method we are generating slug from name attribute.

 

Hope this tutorial will help you. If you have any query, feel free to comment or if you have find any error, you can inform me.


No Comments

Leave a Reply

your email address will not be published. required fields are marked *

*
*