Skip to content

Instantly share code, notes, and snippets.

@RomainSauvaire
Created July 19, 2016 08:30
Show Gist options
  • Save RomainSauvaire/9ae84428f0980741c529bab20b5e4cc2 to your computer and use it in GitHub Desktop.
Save RomainSauvaire/9ae84428f0980741c529bab20b5e4cc2 to your computer and use it in GitHub Desktop.
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