skip to Main Content

Laravel version in composer.json: "laravel/framework": "^8.65"

I have a Laravel backend and I am trying to get all entities from a model that satisfy a condition, and then iterate through them and update some of them according to a certain logic, here’s a simplified version of my code that experiences the same issue I’m having with the actual code:

$entities = SomeModel::where('field1', 1)->get();
$entities->each(function ($entity, $index) {
    $entity->update(['field2' => $index]);
});

I have 5 entities that satisfy field1 == 1 in SomeModel, so after running this code I’d expect one of them to have field2 set to 0, another one set to 1, …, and the last one set to 4.

However, all 5 of them end up with field2 set to 4

I’ve tried using ->fill(['field2' => $index])->save(), I’ve tried using a foreach loop, but I’m still getting the same behaviour where updating an entity in the returned collection seems to update all entities from that collection

2

Answers


  1. You can use Query Builder like this:

    DB::table('some_table')->where('field1', 1)->update([
        'some_field' => 'New value'
    ]);
    

    See here: https://laravel.com/docs/10.x/queries#update-statements

    Login or Signup to reply.
  2. In Laravel , with his amazing ORM eloquent , you can easily get all entities from a model that satisfy a condition and then iterate through them and update some of them just by doing that :

    ( in this example, I want to select all the entities concerned and delete them )

    Model::where('field', value)->get()->map(
       function ($entity) {
         $entity->fill(['is_deleted' => true, 'deleted_at' => date('Y-m-d H:i:s')])->save();
       }
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search