Skip to content

Instantly share code, notes, and snippets.

@ChrisReid
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisReid/52658d191c15895e6e87 to your computer and use it in GitHub Desktop.
Save ChrisReid/52658d191c15895e6e87 to your computer and use it in GitHub Desktop.
Laravel trait to maintain created_at and updated_at columns in Laravel models.
?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Quote extends Model {
use TracksUsers;
}
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
trait TracksUsers {
/**
* Boot the soft deleting trait for a model.
*
* @return void
*/
public static function bootTracksUsers()
{
$userId = \Auth::user() ? \Auth::user()->id : null;
static::creating(function($model) use($userId) {
$model->created_by = $model->created_by ?: $userId;
$model->updated_by = $model->updated_by ?: $userId;
});
static::updating(function($model) use($userId) {
$model->updated_by = $model->updated_by ?: $userId;
});
}
public function creator()
{
return $this->belongsTo(User::class, 'created_by');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment