Home > Software design >  Laravel - Customize model event
Laravel - Customize model event

Time:10-29

So my Comment model has the following model events:

public static function boot()
{
    parent::boot();

    self::created(function ($model) {
        /** @var self $model */
        $model->clearCache();
    });

    self::updated(function ($model) {
        /** @var self $model */
        $model->clearCache();
    });

    self::deleted(function ($model) {
        /** @var self $model */
        $model->clearCache();
    });

However, is there any way I can customize this a bit? So let's say I wanted the Updated Model Event to trigger any time it's updated, but if it's updated a certain way (like having a specific column updated), it could pass a special parameter.

Something like this:

    self::updated(function ($model) {
       if (//// "text" column update)
        $model->clearCache(1);
       } else {
        $model->clearCache(0);
       }
    });

CodePudding user response:

https://laravel.com/api/8.x/Illuminate/Database/Eloquent/Concerns/HasAttributes.html#method_getDirty

getDirty() : Get the attributes that have been changed since the last sync.

self::updated(function ($model) {
   $columns = $model->getDirty();

   foreach ($columns as $column => $newValue) {
     echo $column; // One of the changed columns.
     if ($column == 'YOUR_COLUMN_NAME')
        $model->clearCache(1);
     } else {
        $model->clearCache(0);
   }
}
});

CodePudding user response:

Solution I came up with is to just update the model quietly, then call the function I want while passing the parameter I want:

$comment->saveQuietly();
        
$comment->clearCache($parameter);
  • Related