search
HomePHP FrameworkLaravelDetailed explanation of the two ways of Laravel model events

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. If there is any infringement, please contact admin@php.cn delete
Using Laravel Blade for Frontend Templating in Full-Stack ProjectsUsing Laravel Blade for Frontend Templating in Full-Stack ProjectsMay 01, 2025 am 12:24 AM

LaravelBladeenhancesfrontendtemplatinginfull-stackprojectsbyofferingcleansyntaxandpowerfulfeatures.1)Itallowsforeasyvariabledisplayandcontrolstructures.2)Bladesupportscreatingandreusingcomponents,aidinginmanagingcomplexUIs.3)Itefficientlyhandleslayou

Building a Full-Stack Application with Laravel: A Practical TutorialBuilding a Full-Stack Application with Laravel: A Practical TutorialMay 01, 2025 am 12:23 AM

Laravelisidealforfull-stackapplicationsduetoitselegantsyntax,comprehensiveecosystem,andpowerfulfeatures.1)UseEloquentORMforintuitivebackenddatamanipulation,butavoidN 1queryissues.2)EmployBladetemplatingforcleanfrontendviews,beingcautiousofoverusing@i

What kind of tools did you use for the remote role to stay connected?What kind of tools did you use for the remote role to stay connected?May 01, 2025 am 12:21 AM

Forremotework,IuseZoomforvideocalls,Slackformessaging,Trelloforprojectmanagement,andGitHubforcodecollaboration.1)Zoomisreliableforlargemeetingsbuthastimelimitsonthefreeversion.2)Slackintegrateswellwithothertoolsbutcanleadtonotificationoverload.3)Trel

Remote Access and Screen Sharing: Bridging the Distance for Technical SupportRemote Access and Screen Sharing: Bridging the Distance for Technical SupportMay 01, 2025 am 12:07 AM

Remoteaccessandscreensharingworkbyestablishingasecure,real-timeconnectionbetweencomputersusingprotocolslikeRDP,VNC,orproprietarysolutions.Bestpracticesinclude:1)Buildingtrustthroughclearcommunication,2)Ensuringsecuritywithstrongencryptionandup-to-dat

Is it worth upgrading to the latest Laravel version?Is it worth upgrading to the latest Laravel version?May 01, 2025 am 12:02 AM

Definitely worth considering upgrading to the latest Laravel version. 1) New features and improvements, such as anonymous migration, improve development efficiency and code quality. 2) Security improvement, and known vulnerabilities have been fixed. 3) Community support has been enhanced, providing more resources. 4) Compatibility needs to be evaluated to ensure smooth upgrades.

Laravel logs and error monitoring: Sentry and Bugsnag integrationLaravel logs and error monitoring: Sentry and Bugsnag integrationApr 30, 2025 pm 02:39 PM

Integrating Sentry and Bugsnag in Laravel can improve application stability and performance. 1. Add SentrySDK in composer.json. 2. Add Sentry service provider in config/app.php. 3. Configure SentryDSN in the .env file. 4. Add Sentry error report in App\Exceptions\Handler.php. 5. Use Sentry to catch and report exceptions and add additional context information. 6. Add Bugsnag error report in App\Exceptions\Handler.php. 7. Use Bugsnag monitoring

Why is Laravel still the preferred framework for PHP developers?Why is Laravel still the preferred framework for PHP developers?Apr 30, 2025 pm 02:36 PM

Laravel remains the preferred framework for PHP developers as it excels in development experience, community support and ecosystem. 1) Its elegant syntax and rich feature set, such as EloquentORM and Blade template engines, improve development efficiency and code readability. 2) The huge community provides rich resources and support. 3) Although the learning curve is steep and may lead to increased project complexity, Laravel can significantly improve application performance through reasonable configuration and optimization.

Laravel Live Chat Application: WebSocket and PusherLaravel Live Chat Application: WebSocket and PusherApr 30, 2025 pm 02:33 PM

Building a live chat application in Laravel requires using WebSocket and Pusher. The specific steps include: 1) Configure Pusher information in the .env file; 2) Set the broadcasting driver in the broadcasting.php file to Pusher; 3) Subscribe to the Pusher channel and listen to events using LaravelEcho; 4) Send messages through Pusher API; 5) Implement private channel and user authentication; 6) Perform performance optimization and debugging.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment