Как реализовать красноречивые события в laravel с использованием commmon Trait для всех моделей

Я использую laravel 5.4 для создания веб-приложения.

Я создал черту для реализации событий для созданных, обновленных, удаленных и восстановленных красноречивых событий.

Я создал черту, как показано ниже:

<?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'; } } } 

Но когда я реализую его в своей модели, например:

 <?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' ]; } 

Затем в моем контроллере я вызываю созданное / обновление как обычно через красноречивую модель. Но события не запускаются и не записывают ничего в таблицу действий.

Ниже приведена таблица миграции для активности:

 <?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'); } } 

Пожалуйста, сообщите, в чем проблема?

Я нашел решение, все в порядке с моделью и миграцией, это была черта, в которой он делал проблему. Было нет. что неправильно и что мешает ему работать должным образом.

И самое главное, что было неправильно, это Log, я сделал, я включил правильный класс для него, и это вызвало проблему.

Вот только скорректированный код только для файла признаков.

 <?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'; } } } сети <?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'; } } } 

Пожалуйста, проверьте и сообщите, если что-то не так или может быть сделано лучше.