djmzfKnm
djmzfKnm

Reputation: 27185

How to implement eloquent events in laravel using commmon Trait for all models

I am using laravel 5.4 to create a web app.

I have created a trait to implement events for created, updated, deleted and restored eloquent events.

I have 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;

/**
 * Class ModelEventLogger
 * @package App\Traits
 *
 *  Automatically Log Add, Update, Delete events of Model.
 */
trait ActivityLogger {

    /**
     * Automatically boot with Model, and register Events handler.
     */
    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());//return true;
                }
            });
        }
    }

    /**
     * Set the default events to be recorded if the $recordEvents
     * property does not exist on the model.
     *
     * @return array
     */
    protected static function getRecordActivityEvents()
    {
        if (isset(static::$recordEvents)) {
            return static::$recordEvents;
        }

        return [
            'created',
            'updated',
            'deleted',
            'restored'
        ];
    }

    /**
     * Return Suitable action name for Supplied Event
     *
     * @param $event
     * @return string
     */
    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 am implementing it in my Model like:

<?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 am calling created/update as usual via eloquent model. But the events aren't fired up and not recording anything in the activity table.

Below is my Migration for activity table:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateActivityTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    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();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('activity');
    }
}

Please advise what is the issue?

Upvotes: 4

Views: 3039

Answers (1)

djmzfKnm
djmzfKnm

Reputation: 27185

I found the solution, all ok with Model and Migration, it was the trait where it was making issue. There were a no. of things wrong and which was preventing it to work properly.

And the most important thing which was wrong is the Log, I did;t included proper class for it and that caused the issue.

Here is the corrected code for the trait file only.

<?php

namespace App\Traits;

use Auth;
use Request;
use App\Master\Activity;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

/**
 * Class ModelEventLogger
 * @package App\Traits
 *
 *  Automatically Log Add, Update, Delete events of Model.
 */
trait ActivityLogger {

    /**
     * Automatically boot with Model, and register Events handler.
     */
    protected static function bootActivityLogger()
    {   
        foreach (static::getRecordActivityEvents() as $eventName) {
            static::$eventName(function ($model) use ($eventName) {
                try {
                    $reflect = new \ReflectionClass($model);
                    return Activity::create([
                        'user_id' => Auth::id(),
                        'content_id' => $model->attributes[$model->primaryKey],
                        '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());
                }
            });
        }
    }

    /**
     * Set the default events to be recorded if the $recordEvents
     * property does not exist on the model.
     *
     * @return array
     */
    protected static function getRecordActivityEvents()
    {
        if (isset(static::$recordEvents)) {
            return static::$recordEvents;
        }

        return [
            'created',
            'updated',
            'deleted',
            'restored'
        ];
    }

    /**
     * Return Suitable action name for Supplied Event
     *
     * @param $event
     * @return string
     */
    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';
        }
    }
} 

Please check and advise if anything wrong or could be done in better way.

Upvotes: 2

Related Questions