Search code examples
phplaraveleloquentwhere-in

Laravel Eloquent - bulk update with whereIn array


I'm working on a project where I need to update many rows at once per coin Id.

in order to update all coins values, Im getting them all from the API, so for example I have back:

    $coinsList= [[id="bitcoin", symbol="btc", name="Bintcoin"],[id="etherium", symbol="eth", name="Etherium"]];

and the database table columns is the following:

**| id | coin_id | symbol | name |**

now, I want to update all values to the database, according to the id only, so this is what I did:

    // first get ids from my table
    $exist_ids = Coinlist::all('coin_id')->pluck('coin_id')->toArray();
    
    //get all ids to update (to ignore other ids):
    $updatable_ids = array_values(array_intersect($exist_ids, $allCoinIds));//result for example is: array("bitcoin","etherium");
    
//and now, update the database:
    Coinlist::whereIn('coin_id', $updatable_ids)
                ->update([
                    'symbol' => $coinsList[$key]['symbol'],
                    'name' => $coinsList[$key]['name'],
                    'updated_at' => now()
                ]);

the problem is, I don't have the "$key" in order to update the right row, what am I missing here?

Thanks!


Solution

  • Here is a good way to solve it: in the beginning, I used this library: https://github.com/mavinoo/laravelBatch to update many dynamic rows, but it was really slow, then thanks to Yasin, I moved to: https://github.com/iksaku/laravel-mass-update and now it works way better.

    the implementation is simple, add a simple code to the Model class, then add:

    User::massUpdate(
        values: [
            ['username' => 'iksaku', 'name' => 'Jorge González'],
            ['username' => 'gm_mtz', 'name' => 'Gladys Martínez'],
        ],
        uniqueBy: 'username'
    );
    

    while uniqueBy is the key for the row, and add other columns values to change them dynamically.