Skip to content

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

Merged
taylorotwell merged 1 commit into
laravel:10.xfrom
axlon:fix-replicate-with-unique-ids
Oct 6, 2023
Merged

[10.x] Fix Model::replicate() when using unique keys#48636
taylorotwell merged 1 commit into
laravel:10.xfrom
axlon:fix-replicate-with-unique-ids

Conversation

@axlon
Copy link
Copy Markdown
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
Copy Markdown
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
@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