Skip to content

Instantly share code, notes, and snippets.

@w00p
Created April 2, 2017 16:36
Show Gist options
  • Select an option

  • Save w00p/d38047537dcdfd0dc1da0adb1cddc090 to your computer and use it in GitHub Desktop.

Select an option

Save w00p/d38047537dcdfd0dc1da0adb1cddc090 to your computer and use it in GitHub Desktop.
<?php
namespace App;
use ReflectionClass;
trait RecordsActivity
{
/**
* Register the necessary event listeners.
*
* @return void
*/
protected static function bootRecordsActivity()
{
foreach (static::getModelEvents() as $event) {
static::$event(function ($model) use ($event) {
$model->recordActivity($event);
});
}
}
/**
* Record activity for the model.
*
* @param string $event
* @return void
*/
public function recordActivity($event)
{
Activity::create([
'subject_id' => $this->id,
'subject_type' => get_class($this),
'name' => $this->getActivityName($this, $event),
'user_id' => auth()->user()->id
]);
}
/**
* Prepare the appropriate activity name.
*
* @param mixed $model
* @param string $action
* @return string
*/
protected function getActivityName($model, $action)
{
$name = strtolower((new ReflectionClass($model))->getShortName());
return "{$action}_{$name}";
}
/**
* Get the model events to record activity for.
*
* @return array
*/
protected static function getModelEvents()
{
if (isset(static::$recordEvents)) {
return static::$recordEvents;
}
return [
'created', 'deleted', 'updated'
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment