这篇文章主要给大家分享的是laravel模型事件的内容,laravel模型事件的应用还是比较方便和实用的,因此分享给大家做个参考,感兴趣的朋友就跟随小编来学习一下吧。
Laravel
模型事件的应用 在日常处理一些用户操作事件时,我们有时候需要记录下来,方便以后查阅,或者大数据统计。 Laravel 在模型事件中处理起来很方便,其中Laravel 的模型事件有两种方式,
1.在 2.事件 3.事件监听器 4.之后应用事件
1.在 2.事件监听类的方法 3.之后的效果就是这样了: 以上就是关于laravel模型事件的相关介绍了,上文有对Laravel模型事件的两种方式详细介绍,有这方面学习需要的朋友可以参考,希望本文对大家学习有帮助,更多请关注群英网络其它相关文章。
dispatchesEvents
属性映射事件类php artisan make:model Log
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Log extends Model
{
protected $fillable = ['user_name', 'user_id', 'url', 'event', 'method', 'table', 'description'];
}
php artisan make:migration create_logs_table
<?php
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
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
方法)EventServiceProvider
中的listen
属性绑定好事件PermissionRoleEvent
中的注入两个参数,一个是角色,另一个是attach
或者detach
返回的数组PermissionRoleEventLog
也继承基类LogBaseServer
,这里就是根据传入的数组id遍历,然后创建日志
EventServiceProvider
中的subscribe
属性绑定好处理的类
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2018 群英 版权所有 茂名市群英网络有限公司
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号-36 粤公网安备 44090202000006号 粤工商备P091701000595