Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Add ability to discard Eloquent Model changes #43772

Merged
merged 2 commits into from
Sep 8, 2022

Conversation

crynobone
Copy link
Member

@crynobone crynobone commented Aug 19, 2022

Project::updating(function (Project $model) {
    /*
     * The project update should be a change request
     */
    $changeRequest = new ProjectChangeRequest([
        'original' => array_intersect_key($model->getRawOriginal(), $model->getDirty()),
        'changes' => $model->getDirty(),
    ]);

    $changeRequest->source_model()->associate($model);
    $changeRequest->save();

    // Now we can simply ignore all attribute changes and only save `status="change_request"`
    $model->discardChanges();

    $model->status = 'change_request';
});

Signed-off-by: Mior Muhammad Zaki crynobone@gmail.com

Signed-off-by: Mior Muhammad Zaki <crynobone@gmail.com>
@crynobone crynobone changed the title [9.x] Add ability to discard Eloquent Model changes. [9.x] Add ability to discard Eloquent Model changes Aug 19, 2022
@bernardwiesner
Copy link
Contributor

Seems almost same as this PR: #37756

@bert-w
Copy link
Contributor

bert-w commented Aug 23, 2022

Maybe add an $options parameter to add except/only functionality? Somewhat similar to:

protected function getResourceMethods($defaults, $options)
{
$methods = $defaults;
if (isset($options['only'])) {
$methods = array_intersect($methods, (array) $options['only']);
}
if (isset($options['except'])) {
$methods = array_diff($methods, (array) $options['except']);
}
return $methods;
}

@taylorotwell taylorotwell merged commit 71034a4 into laravel:9.x Sep 8, 2022
@crynobone crynobone deleted the eloquent-discard-changes branch September 9, 2022 01:43
@amitmerchant1990
Copy link
Contributor

Hi!

Just curious about how is it different from refreshing models.

@rodrigopedra
Copy link
Contributor

@amitmerchant1990

refresh() reloads the model data from the database. You do a database call, and can get attributes that might have changed from another requests in the meanwhile.

discardChanges() will, eh, discard any unsaved changes, and return the model to its original state, without performing a database call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

9 participants