Maren Maren
Maren Maren

Reputation: 69

Update all records in database using Laravel

I have this:

$keys = Keys_Info::all();

foreach ($keys as $key)
{
          $rank = 1; //Example.. In real it's variable..
          DB::table('keys_info')
                      ->where('id', $key->id)
                      ->update(['rank' => $rank]);
}

This only updates first row, not all. How get this to update all rows?

EDIT

foreach($keys as $key)
{
   print $key->id; //Example printing all keys
   foreach($results as $results)
   {
            print $key->id; //Example printing all keys

            if (in_array($key->example, $array))
            {
               print $key->id; //Example printing first row key!
               $rank = 1; //Example
               DB::table('keywords_info')
                           ->where('id', $key->id)
                           ->update(['url_rank' => $rank]);
            }
   }
}

I didn't explain well at first, this is whole code I use. I figured out that it does not work in IF statement

Upvotes: 1

Views: 3519

Answers (1)

sumit
sumit

Reputation: 15464

As you are updating all rows you can simply do like below

 DB::table('keys_info')->update(['rank' => $rank]);

If you still want to pass the id you can do like below

//Fetch all ids in array
$keys=Keys_Info::pluck('id')  OR Keys_Info::value('id')
//apply in query
DB::table('keys_info')->whereIn('id', $keys)->update(['rank' => $rank]);

Upvotes: 1

Related Questions