Laravel 9 Model Events Example Tutorial

https://www.itsolutionstuff.com/post/laravel-9-model-events-example-tutorialexample.html

Now, let's see the post of laravel 9 model events example. I would like to show you model events in laravel 9. This article goes in detail on eloquent model events laravel 9. we will help you to give examples of laravel 9 model events created.

Laravel provide list of eloquent model events and each model event have it's own function. it's very helpful. i love laravel eloquent model events.

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

Sometime, we need to add unique number or create slug from title then before create record you need to update this fields at time we can use those time of event. same thing when you update records then also you have to update slug and might when remove records then also you have to delete child records. so event is very helpful and i will say you must have to use when you need this type of situation.

I will explain few important events with example so you will understand how it works and how you can use it.

In this example, i will write down creating, created, updating, updated and deleted events and i will show you one by one example with output in log file so you can easily understand, how model events works.

Create Product Model with events

Here, we will create product model with events. so let's create and put bellow code:

app/Models/Product.php

Now here, we will simply call one by one model method and let's see output:

Create Record: Creating and Created Event

app/Http/Controllers/ProductController.php

Output Log File:

Update Record: Updating and Updated Event

app/Http/Controllers/ProductController.php

Output Log File:

Delete Record: Deleted Event

app/Http/Controllers/ProductController.php

Output Log File:

Read Also: Laravel 9 Socialite Login with Twitter Account Example

Now you can check from your end.

I hope it can help you...

Last updated

Was this helpful?