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

[10.x] Fix Model::replicate() when using unique keys #48636

Merged
merged 1 commit into from
Oct 6, 2023
Merged

[10.x] Fix Model::replicate() when using unique keys #48636

merged 1 commit into from
Oct 6, 2023

Conversation

axlon
Copy link
Contributor

@axlon axlon commented Oct 5, 2023

Fixes #48629

What problem does this PR fix?

When replicating a model, some columns are purposefully omitted from the replica so that the original record will not be overwritten in the database.
By default replication excludes the model's primary key but not any additional unique keys. This means that these keys will need to be excluded manually or manually overwritten before saving. This is only a problem when using HasUuids or HasUlids on columns that are not the model's primary key.

For example, assume the following migration and model:

Schema::create('users', static function (Blueprint $table) {
    $table->id();
    $table->uuid()->unique();
    $table->timestamps();
});
class User extends Model
{
    use HasUuids;

    public function uniqueIds()
    {
        return ['uuid'];
    }
}

The following will fail in a unique constraint violation:

$user = User::firstOrFail();
$otherUser = tap($user->replicate())->save();

@driesvints
Copy link
Member

@axlon can you please add a thorough description and not just link to an issue? thanks

@taylorotwell taylorotwell merged commit 8f1a56d into laravel:10.x Oct 6, 2023
21 checks passed
@axlon axlon deleted the fix-replicate-with-unique-ids branch October 6, 2023 13:32
timacdonald pushed a commit to timacdonald/framework that referenced this pull request Oct 24, 2023
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.

[10.x] Model::replicate() doesn't take into account unique IDs
3 participants