Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save GhazanfarMir/4905f43b33c7669ff5e22a9264a6bb6e to your computer and use it in GitHub Desktop.
Save GhazanfarMir/4905f43b33c7669ff5e22a9264a6bb6e to your computer and use it in GitHub Desktop.
Laravel RecordActivity Trait to store user's activities in a activity table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateActivitiesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('activities', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id')->index();
$table->morphs('subject');
$table->string('type');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('activities');
}
}
<?php
namespace App\Traits;
use App\Activity;
trait RecordsActivity
{
protected static function bootRecordsActivity()
{
if(count(static::getRecordActivityTypes()))
{
foreach(static::getRecordActivities() as $type) {
static::$type(function ($model) use ($type) {
$model->recordsActivity($type);
});
}
}
}
/**
* @param $type
*/
protected function recordsActivity($type)
{
$this->activity()->create([
'user_id' => auth()->id(),
'type' => strtolower((new \ReflectionClass($this))->getShortName()) . "_$type",
]);
}
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function activity()
{
return $this->morphMany(Activity::class, 'subject');
}
/**
* @return array
*/
protected static function getRecordActivityTypes()
{
return ['created'];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment