Featured image of post Application of Laravel Model Events

Application of Laravel Model Events

Triggering logic through model events for future reference or big data statistics.

In daily processing of user operation events, we sometimes need to record them for future reference or big data statistics.

Laravel handles model events conveniently: https://laravel-china.org/docs/laravel/5.5/eloquent#events

There are two approaches to Laravel model events:

  1. Set the dispatchesEvents property to map event classes
  2. Use observers to register events (this article focuses on the second approach)

Implementation Steps

  1. Create Model
    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'];  
}  
  1. Create Migration Table
    php artisan make:migration create_logs_table

    Table structure example (customize as needed):

<?php  

use Illuminate\Support\Facades\Schema;  
use Illuminate\Database\Schema\Blueprint;  
use Illuminate\Database\Migrations\Migration;  

class CreateLogsTable extends Migration  
{  
    public function up()  
    {  
        Schema::create('logs', function (Blueprint $table) {  
            $table->engine = 'InnoDB';  
            $table->increments('id');  
            $table->string('user_id')->comment('Operator\'s ID');  
            $table->string('user_name')->comment('Operator\'s name for quick reference');  
            $table->string('url')->comment('Current operation URL');  
            $table->string('method')->comment('HTTP method of current operation');  
            $table->string('event')->comment('Event type: create, update, delete');  
            $table->string('table')->comment('Affected database table');  
            $table->string('description')->default('');  
            $table->timestamps();  
        });  

        DB::statement("ALTER TABLE `logs` comment 'Operation Log Table'");  
    }  

    public function down()  
    {  
        Schema::dropIfExists('logs');  
    }  
}  
  1. Run Migration
    php artisan migrate

  2. Create Service Provider for Observers
    php artisan make:provider ObserverLogServiceProvider

    Register it in /config/app.php:

  3. Create Base Observer Class
    Create LogBaseServer under app/Observers:

    // Base class handles CLI execution scenarios
    

  4. Implement Model Observer
    Create observer for User model:

  5. Register Observers
    In ObserverLogServiceProvider:

  6. Bind Events to Models
    Example model event registration:

  7. Trigger Events
    Test CRUD operations to populate logs:

Handling Many-to-Many Relationships

  • Note: Methods like attach()/detach() don’t trigger model events.
  1. Bind Custom Event
    In EventServiceProvider:

    protected $listen = [  
        'App\Events\PermissionRoleEvent' => [  
            'App\Listeners\PermissionRoleEventLog',  
        ],  
    ];  
    

  2. Create Event Class
    PermissionRoleEvent with parameters:

  3. Implement Listener
    PermissionRoleEventLog inherits LogBaseServer:

  4. Trigger Event

Handling Login/Logout Events Elegantly

  1. Bind Subscriber
    In EventServiceProvider:

    protected $subscribe = [  
        'App\Listeners\UserEventLog',  
    ];  
    

  2. Implement Event Methods
    In UserEventLog:

  3. Final Results

END