在日常处理一些用户操作事件时,我们有时候需要记录下来,方便以后查阅,或者大数据统计。
Laravel在模型事件中处理起来很方便:https://laravel-china.org/docs/laravel/5.5/eloquent#events
Laravel 的模型事件有两种方式,
dispatchesEvents属性映射事件类php artisan make:model Log<?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<?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 migratephp artisan make:provider ObserverLogServiceProvider/config/app.php中的providers数组注册(大概如图中)






attach方法)





