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

Detailed explanation of the two ways of Laravel model events

Jul 23, 2021 pm 03:03 PM
laravel php

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;];
}
Copy after login
  • 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');
    }
}
Copy after login
  • 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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

What versions of laravel are there? How to choose the version of laravel for beginners What versions of laravel are there? How to choose the version of laravel for beginners Apr 18, 2025 pm 01:03 PM

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

How to view the version number of laravel? How to view the version number of laravel How to view the version number of laravel? How to view the version number of laravel Apr 18, 2025 pm 01:00 PM

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

The difference between laravel and thinkphp The difference between laravel and thinkphp Apr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

See all articles