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

Fix can't save the same model twice #2658

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Conversation

erikn69
Copy link
Contributor

@erikn69 erikn69 commented Apr 19, 2024

This doesn't solve the problem completely Another approach seems to work

$user->save();
//$user = $user->fresh();
$user->save();

@drbyte
Copy link
Collaborator

drbyte commented Apr 19, 2024

Right. I'm wondering the same thing.

@drbyte
Copy link
Collaborator

drbyte commented Apr 20, 2024

Would this be safe instead?

-    $model->roles()->attach($roles, $teamPivot);
+    $currentRoles = $model->roles->map(fn ($role) => $role->getKey())->toArray();
+    $model->roles()->attach(array_diff($roles, $currentRoles), $teamPivot);

@erikn69
Copy link
Contributor Author

erikn69 commented May 6, 2024

set a flag

Seems, to work
I don't know if Laravel has a way to remove the callback after a single execution or if you can locate and remove the callback.

$class = \get_class($model);
$saved = false;

$class::saved(
    function ($object) use ($permissions, $model, $teamPivot, &$saved) {
        if ($saved || $model->getKey() != $object->getKey()) {
            return;
        }
        $model->permissions()->attach($permissions, $teamPivot);
        $model->unsetRelation('permissions');
        $saved = true;
    }
);

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.

Cannot save the user model twice in the same request
2 participants