Home  >  Article  >  PHP Framework  >  Detailed explanation of the two ways of Laravel model events

Detailed explanation of the two ways of Laravel model events

藏色散人
藏色散人forward
2021-07-23 15:03:052744browse

When dealing with some user operation events on a daily basis, we sometimes need to record them , for later reference or big data statistics.


Laravel is very convenient to handle in model events: https://laravel-china.org/docs/laravel/5.5/eloquent#events


Laravel’s model There are two ways of events,

  • SettingdispatchesEventsProperty mapping event class
  • Use observers to register events, here is the second one
  • New model

php artisan make:model Log

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Log extends Model
{
    protected $fillable = [&#39;user_name&#39;, &#39;user_id&#39;, &#39;url&#39;, &#39;event&#39;, &#39;method&#39;, &#39;table&#39;, &#39;description&#39;];
}
  • Create migration table:

php artisan make:migration create_logs_table

  • The structure of the table is roughly like this, it can be designed as needed
<?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(&#39;logs&#39;, 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');
    }
}
  • Run the migration to generate the table

php artisan migrate

  • Create a new service provider to uniformly register all model event observers (the subsequent names can be more vivid)

php artisan make:provider ObserverLogServiceProvider

  • to the providers array in /config/app.php Register (roughly as shown in the picture)

Detailed explanation of the two ways of Laravel model events

    ##Create a new folder in the
  • app directory Observers Store model observers, and create a new base class LogBaseServer and build basic attributes in the constructor (CLI is because there is no user execution when executing from the command line)

Detailed explanation of the two ways of Laravel model events

##Create a new observer inheriting the base class
    LogBaseServer
  • (User model, method The name should correspond to the event in the document)

Detailed explanation of the two ways of Laravel model events##To the newly created service provider

ObserverLogServiceProvider
    Run in

Detailed explanation of the two ways of Laravel model events Register events for the required models (I have quite a few, it will probably look like this in the future )

Detailed explanation of the two ways of Laravel model eventsThen we trigger some events (addition, deletion and modification, the table data will be available)

Detailed explanation of the two ways of Laravel model events##Many-to-many association insertion will not trigger the model (such as

attach
Method)
  • At this time, you need to create a new event class to simulate (here is a rough introduction to assigning permissions to roles)
  • 1. In
  • EventServiceProvider
listen

The attribute is bound to the event

2. Injection two in the eventDetailed explanation of the two ways of Laravel model eventsPermissionRoleEvent Parameters, one is the role, the other is the array returned by

attach

or detach

##

3. Event listenerPermissionRoleEventLog also inherits the base class LogBaseServer, here it is traversed according to the incoming array id, and then creates a log

Detailed explanation of the two ways of Laravel model events

4. Then apply the event

Detailed explanation of the two ways of Laravel model events


  • Update Handle login and logout events gracefully

1. Bind the subscribe attribute in EventServiceProvider to a well-handled class

Detailed explanation of the two ways of Laravel model events

2. Methods of the event listening class

Detailed explanation of the two ways of Laravel model events

3. After The effect is like this:

Detailed explanation of the two ways of Laravel model events

#Related recommendations:The latest five Laravel video tutorial

#

The above is the detailed content of Detailed explanation of the two ways of Laravel model events. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete