Laravel - how to save if there is a change in the model

Asked

Viewed 301 times

0

Good afternoon guys, I have a problem which is as follows would like to know if Laravel has any method to check if any changes were made before saving the model Example.

table users, if the user requested to edit the name, but did not change anything, and have saved, is accepted in good! but I would like you to save only if there really was a change!

for my research there is a method isDirty but I don’t understand your concept.

OBS: I exemplified a simple model, could do the check manual, but let’s think of a much larger model with many attributes, it would not be feasible to carry out manually.

if someone can give the path of the stones I am happy!

1 answer

0

This is the code of the method save() of Laravel version 5.3

public function save(array $options = [])
{
    $query = $this->newQueryWithoutScopes();
    // If the "saving" event returns false we'll bail out of the save and return
    // false, indicating that the save failed. This provides a chance for any
    // listeners to cancel save operations if validations fail or whatever.
    if ($this->fireModelEvent('saving') === false) {
        return false;
    }
    // If the model already exists in the database we can just update our record
    // that is already in this database using the current IDs in this "where"
    // clause to only update this model. Otherwise, we'll just insert them.
    if ($this->exists) {
        $saved = $this->isDirty() ?
                    $this->performUpdate($query) : true;
    }
    // If the model is brand new, we'll insert it into our database and set the
    // ID attribute on the model to the value of the newly inserted row's ID
    // which is typically an auto-increment value managed by the database.
    else {
        $saved = $this->performInsert($query);
    }
    if ($saved) {
        $this->finishSave($options);
    }
    return $saved;
}

note the following in your own code already runs the method isDirty, that is, what you want to verify the code itself of the Eloquent already makes.

This is very clear when you have the setting for the field updated_at which is the date and time of the last change in the record, if it is not changed this data continues with the date and time without updating, only there is change when there are changes in your field(s) and call the method save().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.