在平常處理一些用戶操做事件時,咱們有時候須要記錄下來,方便之後查閱,或者大數據統計。php
Laravel 在模型事件中處理起來很方便:https://laravel-china.org/docs/laravel/5.5/eloquent#eventslaravel
Laravel 的模型事件有兩種方式,數組
dispatchesEvents
屬性映射事件類php artisan make:model Log
app
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Log extends Model { protected $fillable = ['user_name', 'user_id', 'url', 'event', 'method', 'table', 'description']; }
php artisan make:migration create_logs_table
ide
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateLogsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('logs', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('user_id')->comment('操做人的ID'); $table->string('user_name')->comment('操做人的名字,方便直接查閱'); $table->string('url')->comment('當前操做的URL'); $table->string('method')->comment('當前操做的請求方法'); $table->string('event')->comment('當前操做的事件,create,update,delete'); $table->string('table')->comment('操做的表'); $table->string('description')->default(''); $table->timestamps(); }); DB::statement("ALTER TABLE `logs` comment '操做日誌表'"); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('logs'); } }
php artisan migrate
函數
php artisan make:provider ObserverLogServiceProvider
大數據
/config/app.php
中的providers
數組註冊(大概如圖中)app
目錄下新建文件夾Observers
存放模型觀察器,並新建基類LogBaseServer
並在構造函數構建基本屬性(CLI是由於在命令行執行時不存在用戶執行)LogBaseServer
(User模型,方法的名字要對應文檔中的事件)ObserverLogServiceProvider
中運行attach
方法)1.在EventServiceProvider
中的listen
屬性綁定好事件url
2.事件PermissionRoleEvent
中的注入兩個參數,一個是角色,另外一個是attach
或者detach
返回的數組spa
3.事件監聽器PermissionRoleEventLog
也繼承基類LogBaseServer
,這裏就是根據傳入的數組id遍歷,而後建立日誌命令行
4.以後應用事件
1.在EventServiceProvider
中的subscribe
屬性綁定好處理的類
2.事件監聽類的方法
3.以後的效果就是這樣了:
END
原文地址