Last active
July 13, 2016 08:50
-
-
Save wdog/2b54e6f26646e93b764a29709127ee8c to your computer and use it in GitHub Desktop.
TRAIT LOG ACTIVITY
This file contains 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\Wdog\Traits; | |
use App\Wdog\Entities\LogAction; | |
use Auth; | |
use Carbon\Carbon; | |
use Illuminate\Database\Eloquent\Model; | |
/** | |
* Class ModelEventLogger | |
* @package App\Wdog\Traits | |
*/ | |
trait ModelEventLogger | |
{ | |
static $recordEvents = null; | |
/** | |
* | |
*/ | |
public static function bootModelEventLogger() | |
{ | |
foreach (static::getRecordActivityEvents() as $eventName) { | |
static::$eventName(function (Model $model) use ($user_id, $eventName) { | |
$log = new LogAction([ | |
'user_id' => Auth::user()->id, | |
'dt_action' => Carbon::now(), | |
'action' => $eventName | |
]); | |
$model->logs()->save($log); | |
}); | |
} | |
} | |
/** | |
* @return array | |
*/ | |
protected static function getRecordActivityEvents() | |
{ | |
if (isset(static::$recordEvents)) { | |
return static::$recordEvents; | |
} | |
return [ | |
'created', | |
'updated', | |
'deleted', | |
]; | |
} | |
/** | |
* @return | |
* @internal param Model $model | |
*/ | |
public function logs() | |
{ | |
return $this->morphMany('\App\Wdog\Entities\LogAction', 'loggable')->orderBy('dt_action', 'desc'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
see for complete example http://stackoverflow.com/questions/31087897/laravel-5-log-model-create-update-delete-events/38241570#38241570