Laravel deleting wrong Model with delete() call

Viewed 75

My model Service has a composite primary key, I'm trying to delete only version 2, but on calling delete() of that model, Eloquent also deletes the first version (which has the same id, but different version.

dump(Service::where("id", $serviceId)->where("version", 1)->count());

$service = Service::where("id", $serviceId)->where("version", 2)->first();
$service->delete();

dd(Service::where("id", $serviceId)->where("version", 1)->count());

The output of the dump() before the delete() is 1, and output of dd() is 0. I've verified the $service is the correct model with the correct version.

Here's my key setup on the Services table:

$table->unique(["id", "item_id", "version"]);

What's going wrong here? Is my code wrong, or is something going wrong with Eloquent?

1 Answers

Use the delete() method from Builder:

Service::where("id", $serviceId)->where("version", 2)->delete();


Eloquent does not handle properly composite primary keys. The delete() method from Model delete all records that matches the id field.

Here is a better explanation and a workaround if you really want to use composite primary keys: https://github.com/laravel/framework/issues/5355

And from Laravel Docs.

Related