Laravel 9 Model Events Every Developer Should Know
Posted
Mahedi Hasan
Category
Laravel 9
Published
September 14, 2022
Hello artisan,
If you work on react js, Vue js, or WordPress, you will notice that there are some basic hooks to functionalize the corresponding language. Laravel has some model events that are automatically called when a model makes some changes.
In this tutorial, I will share with you some knowledge of Laravel model events and how we can use them in our code to make it dynamic. Assume, you would like to trigger something having changed a model data. You know, we can call model events in this situation.
There are so many model events in Laravel 9. Such as creating
, created
, updating
, updated
, saving
, saved
, deleting
, deleted
, restoring
, restored
. Events allow you to easily execute code each time a specific model class is saved or updated in the database.
Take a brief look:
- 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
Let’s see an example of the use case of model events in Laravel:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Log;
use Str;
class Product extends Model
{
use HasFactory;
public static function boot() {
parent::boot();
static::creating(function($item) {
Log::info('This event will call before creating data');
//you can write you any logic here like:
$item->slug = Str::slug($item->name);
});
static::created(function($item) {
Log::info('This event will call after creating data');
});
static::updating(function($item) {
Log::info('This event will call before updating data');
});
static::updated(function($item) {
Log::info('This event will call after updating data');
});
static::deleted(function($item) {
Log::info('This event will call after deleting data');
});
}
}
You can also use $dispatchesEvents
property of a model to call an event like:
protected $dispatchesEvents = [
'saved' => \App\Events\TestEvent::class,
];
This TestEvent
will call after saving the data. You write your logic inside TestEvent the
class. Hope it can help you.
Read also: How to Use Laravel Model Events
Hope it can help you.
Laravel News Links