I work on a Laravel 9.0 project that uses Eloquent models to represent objects and store them in the DB. Most of the time, Eloquent works as expected.
However when I need to load a list of objects from the db, add/remove items to the list and then resave the list in the db (by deleting the old list elements and inserting the new ones), it just does not work: the old elements are deleted, but the new elements are not saved by the Model::save method.
There is no error message and the save method returns true. Please see the below test code and let me know, what is wrong and how to fix it:
//loading contract attachments
$atts = Attachment::where('contract_id', 386)->get();
//deleting old attachments in the db
Attachment::where('contract_id', 386)->delete();
//placeholder for code to add/remove elements from the attachements list in the memory
//reinserting the attachement list to the db
foreach ($atts as $a ) {
//unsetting the id to force a new insert
unset($a->id);
$a->save();
}
In the debugger, I can see that the attachments look good in memory, when I`m trying to insert them:
I would personally replicate the models, save them to the database and then delete the old models:
$atts = Attachment::where('contract_id', 386)->get();
foreach ($atts as $a ) {
$a->replicate()->save();
}
I did not test this code.