Last active
July 6, 2017 09:19
-
-
Save GhazanfarMir/4905f43b33c7669ff5e22a9264a6bb6e to your computer and use it in GitHub Desktop.
Laravel RecordActivity Trait to store user's activities in a activity table
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 | |
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'); | |
} | |
} |
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\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