Home PHP Framework Laravel Quick Start with Laravel Model Events

Quick Start with Laravel Model Events

May 01, 2020 pm 01:07 PM
laravel

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;
    }
}
Copy after login

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,
];
Copy after login

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;
    }
}
Copy after login

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(&#39;log&#39;)->info($event->user);
    }
}
Copy after login

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,
        ],
    ];
    // ...
}
Copy after login

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,
   }
Copy after login

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"}
Copy after login

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
>>>
Copy after login

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, &#39;paul&#39;) !== false) {
        return false;
    }
}
Copy after login

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(&#39;saving&#39;) === false) {
        return false;
    }
Copy after login

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)
    {
        //
    }
}
Copy after login

You can register an observer in the boot() method of the service provider AppServiceProvider.

/**
 * 运行所有应用服务。
 *
 * @return void
 */
public function boot()
{
    User::observe(UserObserver::class);
}
Copy after login

推荐教程:《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!

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)

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Mar 31, 2025 pm 11:24 PM

Laravel schedule task run unresponsive troubleshooting When using Laravel's schedule task scheduling, many developers will encounter this problem: schedule:run...

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

Laravel - Dump Server Laravel - Dump Server Aug 27, 2024 am 10:51 AM

Laravel - Dump Server - Laravel dump server comes with the version of Laravel 5.7. The previous versions do not include any dump server. Dump server will be a development dependency in laravel/laravel composer file.

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Apr 01, 2025 am 09:09 AM

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

Laravel - Action URL Laravel - Action URL Aug 27, 2024 am 10:51 AM

Laravel - Action URL - Laravel 5.7 introduces a new feature called “callable action URL”. This feature is similar to the one in Laravel 5.6 which accepts string in action method. The main purpose of the new syntax introduced Laravel 5.7 is to directl

See all articles