I am using laravel 5.4 to build a web application.
I created a trait for implementing events for created, updated, deleted, and restored eloquent events.
I created a trait as below:
<?php
namespace App\Traits;
use Auth;
use App\Master\Activity;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
trait ActivityLogger {
protected static function boot()
{
parent::boot();
foreach (static::getRecordActivityEvents() as $eventName) {
static::$eventName(function (Model $model) use ($eventName) {
try {
$reflect = new \ReflectionClass($model);
return Activity::create([
'user_id' => Auth::user()->id,
'content_id' => $model->id,
'content_type' => get_class($model),
'action' => static::getActionName($eventName),
'description' => ucfirst($eventName) . " a " . $reflect->getShortName(),
'details' => json_encode($model->getDirty()),
'ip_address' => Request::ip()
]);
} catch (\Exception $e) {
Log::debug($e->getMessage());
}
});
}
}
protected static function getRecordActivityEvents()
{
if (isset(static::$recordEvents)) {
return static::$recordEvents;
}
return [
'created',
'updated',
'deleted',
'restored'
];
}
protected static function getActionName($event)
{
switch (strtolower($event)) {
case 'created':
return 'create';
break;
case 'updated':
return 'update';
break;
case 'deleted':
return 'delete';
break;
case 'restored':
return 'restore';
break;
default:
return 'unknown';
}
}
}
But when I implement it in my Model , for example:
<?php
namespace App\Master;
use App\Traits\ActivityLogger;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class LeadSource extends Model
{
use ActivityLogger;
use SoftDeletes;
protected $table = 'lead_source';
protected $primaryKey = 'lead_source_id';
protected $dates = ['deleted_at'];
protected $fillable = [
'name', 'created_by', 'created_ip', 'updated_by', 'updated_ip'
];
}
Then in my controller, I invoke the created / updated, as usual, using an eloquent model. But events do not fire and write nothing to the action table.
Below is my Migration for action table:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateActivityTable extends Migration
{
public function up()
{
Schema::create('activity', function (Blueprint $table) {
$table->increments('activity_id');
$table->unsignedInteger('user_id');
$table->unsignedInteger('content_id');
$table->string('content_type', 255);
$table->string('action', 255);
$table->text('description')->nullable();
$table->longText('details')->nullable();
$table->ipAddress('ip_address')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('activity');
}
}
Please report what is the problem?