Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Responsible trait for Eloquent to track changes
<?php
// https://klyp.co/blog/technology/five-awesome-code-snippets-enhance-your-next-laravel-project
namespace App\Models\Traits;
use Auth;
trait Responsible
{
/**
* Boot trait.
*
* @return void
*/
public static function bootResponsible()
{
// Prepare authenticated user id
$userId = Auth::id();
// Register saving event listener
static::saving(function ($model) use ($userId) {
$model->created_by = $model->created_by ?: $userId;
$model->updated_by = $userId;
}, 10);
// Register deleting event listener
static::deleting(function ($model) use ($userId) {
$model->deleted_by = $userId;
$model->save();
}, 10);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment