Laravel 模型事件的应用

2018-03-18 21:41:44 +08:00
 DavidNineRoc

在日常处理一些用户操作事件时,我们有时候需要记录下来,方便以后查阅,或者大数据统计。


Laravel 在模型事件中处理起来很方便:https://laravel-china.org/docs/laravel/5.5/eloquent#events


Laravel 的模型事件有两种方式,

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Log extends Model
{
    protected $fillable = ['user_name', 'user_id', 'url', 'event', 'method', 'table', 'description'];
}

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

  1. EventServiceProvider中的listen属性绑定好事件
  2. 事件PermissionRoleEvent中的注入两个参数,一个是角色,另一个是attach或者detach返回的数组
  3. 事件监听器PermissionRoleEventLog也继承基类LogBaseServer,这里就是根据传入的数组 id 遍历,然后创建日志
  4. 之后应用事件

  1. EventServiceProvider中的subscribe属性绑定好处理的类
  2. 事件监听类的方法
  3. 之后的效果就是这样了:

END

原文地址

2502 次点击
所在节点    PHP
5 条回复
dongisking
2018-03-18 23:03:18 +08:00
用手机看你的真难受啊
crystom
2018-03-19 10:46:15 +08:00
phpstudy 亮了
DavidNineRoc
2018-03-19 11:29:04 +08:00
@dongisking 那就用电脑把~~~

@crystom linux 上部署可以自己折腾,在 windows 我没什么追求,只要快速方便就行。何必装这个大笔,同时启动一个服务器还要打开命令行什么什么的,我直接单击,
RorschachZZZ
2018-03-19 14:25:51 +08:00
码。我的用户行为记录一直用中间件做的。。。。
aksoft
2018-03-20 16:18:49 +08:00
挺好,php 是世界上最好的语言

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/439192

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX