Home > PHP Framework > Laravel > A brief analysis of the difference between isDirty() and wasChanged() in Laravel

A brief analysis of the difference between isDirty() and wasChanged() in Laravel

青灯夜游
Release: 2023-01-04 21:23:20
forward
1613 people have browsed it

This article will talk about the difference between isDirty() and wasChanged() in Laravel data model. I hope it will be helpful to everyone!

A brief analysis of the difference between isDirty() and wasChanged() in Laravel

Is there a difference between `isDirty()` and `wasChanged()` in the Laravel data model?

Answer: There is a difference.

Related code: github.com/laravel/framework/blob/...

The code of the isDirty function is as follows:

/**
 * 判断模型或者任意指定模型属性是否被修改过
 *
 * @param  array|string|null  $attributes
 * @return bool
 */public function isDirty($attributes = null){
    return $this->hasChanges(
        $this->getDirty(), is_array($attributes) ? $attributes : func_get_args()
    );}
Copy after login

The code of getChanges() and getDirty() functions is as follows

/**
 * 获取自从最后一次同步以来,被修改的属性值
 *
 * @return array
 */public function getDirty(){
    $dirty = [];
    foreach ($this->getAttributes() as $key => $value) {
        if (! $this->originalIsEquivalent($key, $value)) {
            $dirty[$key] = $value;
        }
    }
    return $dirty;}/**
 * 获取所有已经被修改的属性.
 *
 * @return array
 */public function getChanges(){
    return $this->changes;}
Copy after login

In short.

The answer is quoted from: laracasts.com/discuss/channels/elo...

isDirty (and getDirty) is used for pre-save execution to see which properties have been modified between retrieval from the database and call, while wasChanged (and getChanges) is used for post-save execution to see Whether the property was modified or updated in the last save (from code to database).

Original address: https://stackoverflow.com/questions/58312036/incoherence-between-eloquent -isdirty-and-getchanges

Translation address: https://learnku.com/laravel/t/61576

[Related recommendations: laravel video tutorial

The above is the detailed content of A brief analysis of the difference between isDirty() and wasChanged() in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:learnku.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template