Last active
August 29, 2015 14:21
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
?php namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
class Quote extends Model { | |
use TracksUsers; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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