Laravel model events allow you to monitor multiple key points in the model life cycle and even prevent a model from being saved or deleted. The Laravel Model Events documentation provides an overview of how to use hooks to associate corresponding events with related event types, but the main focus of this article is the construction and setup of events and listeners, with some additional details.
Event Overview
Eloquent has many events that allow you to connect them using hooks and add custom functionality to your models. The model starts with the following events:
retrieved
creating
created
updating
updated
saving
saved
deleting
deleted
restoring
restored
We can learn about them from the documentation. How is it implemented? You can also enter the base class of Model to see how they are implemented:
When the existing model is retrieved from the database, the retrieved event will be triggered. When a new model is saved for the first time, the creating and created events will fire. If the save method is called on a model that already exists in the database, the updating / updated event will be triggered. Regardless, in both cases, the saving / saved events will fire.
The documentation gives a good overview of model events and explains how to use hooks to associate events, but if you are a beginner or are not familiar with how to use hooks to connect event listeners to these customizations Model events are associated, please read further in this article.
Registering Events
In order to associate an event in your model, the first thing you need to do is to register the event object using the $dispatchesEvents property, which ultimately Will be triggered by HasEvents::fireCustomModelEvent() method, which will be called by fireModelEvent() method. The original fireCustomModelEvent() method is roughly as follows:
/** * 为给定的事件触发一个自定义模型。 * * @param string $event * @param string $method * @return mixed|null */ protected function fireCustomModelEvent($event, $method) { if (! isset($this->dispatchesEvents[$event])) { return; } $result = static::$dispatcher->$method(new $this->dispatchesEvents[$event]($this)); if (! is_null($result)) { return $result; } }
Some events, such as delete, will be detected to determine whether the event will return false and then exit the operation. For example, you can use this hook to do some detection and prevent a user from being created or deleted.
Using the App\User model for example, here shows how to configure your model event:
protected $dispatchesEvents = [ 'saving' => \App\Events\UserSaving::class, ];
You can use the artisan make:event command to create this event for you, but basically this will This is what you end up with:
<?php namespace App\Events; use App\User; use Illuminate\Queue\SerializesModels; class UserSaving { use SerializesModels; public $user; /** * 创建一个新的事件实例 * * @param \App\User $user */ public function __construct(User $user) { $this->user = $user; } }
Our event provides a public $user property so that you can access the User model instance during the saving event.
The next thing you need to do in order to make it work is to set up an actual listener for this event. We set the triggering time of the model. When the User model triggers the saving event, the listener will be called.
Create an event listener
Now, we define the User model and register an event listener to listen for the saving event to be triggered. Although I was able to do this quickly with model observers, I want to walk you through configuring event listeners for individual event triggers.
Event Listener Just like other event listeners in Laravel, the handle() method will receive an instance of the App\Events\UserSaving event class.
You can create it manually or use the php artisan make:listener command. Regardless, you will create a listener class like this:
<?php namespace App\Listeners; use App\Events\UserSaving as UserSavingEvent; class UserSaving { /** * 处理事件。 * * @param \App\Events\UserSavingEvent $event * @return mixed */ public function handle(UserSavingEvent $event) { app('log')->info($event->user); } }
I just added a logging call to make it easier to inspect the model passed to the listener. To do this, we also need to register a listener in the EventServiceProvider::$listen property:
<?php namespace App\Providers; use Illuminate\Support\Facades\Event; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; class EventServiceProvider extends ServiceProvider { /** * 应用的事件监听器。 * * @var array */ protected $listen = [ \App\Events\UserSaving::class => [ \App\Listeners\UserSaving::class, ], ]; // ... }
Now, when the model calls the saving event, the event listener we registered will also be triggered and executed.
Try event monitoring
We can quickly generate event monitoring code through the tinker session:
php artisan tinker >>> factory(\App\User::class)->create(); => App\User {#794 name: "Aiden Cremin", email: "josie05@example.com", updated_at: "2018-03-15 03:57:18", created_at: "2018-03-15 03:57:18", id: 2, }
If you have correctly registered the event and listener, You should be able to see the JSON expression of the model in the laravel.log file:
[2018-03-15 03:57:18] local.INFO: {"name":"Aiden Cremin","email":"josie05@example.com"}
One thing to note is that the model does not have created_at or updated_at attributes at this time. If save() is called again on the model, there will be a new record with a timestamp on the log, because the saving event fires on newly created records or existing records:
>>> $u = factory(\App\User::class)->create(); => App\User {#741 name: "Eloisa Hirthe", email: "gottlieb.itzel@example.com", updated_at: "2018-03-15 03:59:37", created_at: "2018-03-15 03:59:37", id: 3, } >>> $u->save(); => true >>>
Stop a save operation
Some model events allow you to perform blocking operations. To give a ridiculous example, suppose we do not allow any user's model to save its attribute $user->name. The content is Paul:
/** * 处理事件。 * * @param \App\Events\UserSaving $event * @return mixed */ public function handle(UserSaving $event) { if (stripos($event->user->name, 'paul') !== false) { return false; } }
In the Model::save() method of Eloquent, it will be based on The return result of event monitoring determines whether to stop saving:
public function save(array $options = []) { $query = $this->newQueryWithoutScopes(); // 如果 "saving" 事件返回 false ,我们将退出保存并返回 // false,表示保存失败。这为服务监听者提供了一个机会, // 当验证失败或者出现其它任何情况,都可以取消保存操作。 if ($this->fireModelEvent('saving') === false) { return false; }
This save() is a good example. It tells you how to customize events in the model life cycle and passively perform log data recording or Task scheduling.
Using Observers
If you are listening to multiple events, then you may find it more convenient to use an observer class to group the events by type. Here is an example Eloquent observer:
<?php namespace App\Observers; use App\User; class UserObserver { /** * 监听 User 创建事件。 * * @param \App\User $user * @return void */ public function created(User $user) { // } /** * 监听 User 删除事件。 * * @param \App\User $user * @return void */ public function deleting(User $user) { // } }
You can register an observer in the boot() method of the service provider AppServiceProvider.
/** * 运行所有应用服务。 * * @return void */ public function boot() { User::observe(UserObserver::class); }
推荐教程:《Laravel教程》
The above is the detailed content of Quick Start with Laravel Model Events. For more information, please follow other related articles on the PHP Chinese website!

Laravel stands out by simplifying the web development process and delivering powerful features. Its advantages include: 1) concise syntax and powerful ORM system, 2) efficient routing and authentication system, 3) rich third-party library support, allowing developers to focus on writing elegant code and improve development efficiency.

Laravelispredominantlyabackendframework,designedforserver-sidelogic,databasemanagement,andAPIdevelopment,thoughitalsosupportsfrontenddevelopmentwithBladetemplates.

Laravel and Python have their own advantages and disadvantages in terms of performance and scalability. Laravel improves performance through asynchronous processing and queueing systems, but due to PHP limitations, there may be bottlenecks when high concurrency is present; Python performs well with the asynchronous framework and a powerful library ecosystem, but is affected by GIL in a multi-threaded environment.

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

Laravel can be used for front-end development. 1) Use the Blade template engine to generate HTML. 2) Integrate Vite to manage front-end resources. 3) Build SPA, PWA or static website. 4) Combine routing, middleware and EloquentORM to create a complete web application.

PHP and Laravel can be used to build efficient server-side applications. 1.PHP is an open source scripting language suitable for web development. 2.Laravel provides routing, controller, EloquentORM, Blade template engine and other functions to simplify development. 3. Improve application performance and security through caching, code optimization and security measures. 4. Test and deployment strategies to ensure stable operation of applications.

Laravel and Python have their own advantages and disadvantages in terms of learning curve and ease of use. Laravel is suitable for rapid development of web applications. The learning curve is relatively flat, but it takes time to master advanced functions. Python's grammar is concise and the learning curve is flat, but dynamic type systems need to be cautious.

Laravel's advantages in back-end development include: 1) elegant syntax and EloquentORM simplify the development process; 2) rich ecosystem and active community support; 3) improved development efficiency and code quality. Laravel's design allows developers to develop more efficiently and improve code quality through its powerful features and tools.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software