4

I am updating multiple rows in laravel .

 StoragePeriod::where('customer_id', $invoice->customer_id)->update(['invoice_id' => $invoice->id]);

How I can get ids of those updated records?

  • the return value of the above statement will contain it, so `$sPModel = StoragePeriod::where('cust ...`, the pluck the ids from it, using `$sPModel->pluck('id');` – bhucho Apr 07 '21 at 08:08
  • That is a work around –  Apr 07 '21 at 08:11

1 Answers1

3

You can use the tap method.

If you wish to get all the models instead of just the ids you can replace pluck with get.

tap(StoragePeriod::where('customer_id', $invoice->customer_id))
    ->update(['invoice_id' => $invoice->id])
    ->pluck('id');

From the documentation:

If no closure is passed to the tap function, you may call any method on the given $value. The return value of the method you call will always be $value, regardless of what the method actually returns in its definition. For example, the Eloquent update method typically returns an integer. However, we can force the method to return the model itself by chaining the update method call through the tap function:

$user = tap($user)->update([
    'name' => $name,
    'email' => $email, 
]);
Linus Juhlin
  • 1,175
  • 10
  • 31