I'm using the mongodb/laravel-mongodb package in a Laravel project and running into an issue with documents that have both _id and id fields.
For example, a document in my collection looks like this:
{
"_id": ObjectId("68de3600f72aacb41204351d"),
"id": "custom123",
"name": "Example"
}
When I try to update it using Eloquent:
$doc = CustomHtml::where('_id', '68de3600f72aacb41204351d')->first();
$doc->name = "Updated Example";
$doc->save();
The update fails or doesn't behave as expected.
I suspect the issue comes from the package automatically mapping the _id field to the Eloquent id property, which conflicts with my custom id.
What I want:
Keep the _id as the MongoDB ObjectId.
Keep my id as a separate custom identifier.
Be able to update the document using Eloquent without removing either field.
Question: Is there a way to disable the automatic _id ↔ id mapping in mongodb/laravel-mongodb so that Eloquent can work with documents containing both _id and id fields?
_idandid. My recommendation is to scrapid, as you are misusing it (relative to how the FRAMEWORK works). If you want to have your own columns and stuff like that in a database, do it, but know that the framework is adpated to work in a way, and you are completely going over it not caring about it, so you will have these issues and they are very annoying. The easiest solution would be to renameidto something that is relevant, what isidif you already have_id? simply renameidto something else and done!idas the mainid, but mongo uses_id. This is mostly a driver issue, as you are describing, because you had no issues with another package. Still, Laravel will always treatidas the mainid, so the other driver was wrong or something like that. Either way, to try to help you, I would do what the answer to your question says. Is chaging$primaryKeyto_idnot working? Check how the driver works behind sceens so you check why is not using$primaryKeycorrectly. Maybe it is a bug