1

I am trying to update multiple rows of data with existing foreign key values where basket should only link to the foreign ID of 100.

Example:

id title basket_id (foreign key to another table)
1 apple 100
2 banana 200
2 kiwi 300

What I have tried:

$fruits = Fruit::whereIn('basket', [200, 300])->get();

foreach ($fruits as $fruit) {
  $fruit->update([
    "basket_id" => 100
  ])
}

This works fine, however, when I print $fruit, I am still getting the old basket_id in the relations attribute in eloquent.

Am I missing a step?

Thanks

cafe123
  • 55
  • 6

1 Answers1

1

To fetch it, you can use the fresh() or refresh() on $fruit object, like this:

$fruits = Fruit::whereIn('basket', [200, 300])->get();

foreach ($fruits as $fruit) {
  $fruit->update([
    "basket_id" => 100
  ]);
  $fruit->refresh(); // Fetch updated object
}

https://laravel.com/docs/10.x/eloquent#refreshing-models

The fresh method will re-retrieve the model from the database. The existing model instance will not be affected:

$flight = Flight::where('number', 'FR 900')->first();
$freshFlight = $flight->fresh();

The refresh method will re-hydrate the existing model using fresh data from the database. In addition, all of its loaded relationships will be refreshed as well:

$flight = Flight::where('number', 'FR 900')->first();
$flight->number = 'FR 456';
$flight->refresh();
$flight->number; // "FR 900"
Wahyu Kristianto
  • 8,719
  • 6
  • 43
  • 68