John Davidson

php - How to count number of rows that gets updated

0 comments
Message:


I have made this code for the Controller:


public function updateUncompletedCarts(Request $request)
{
$uncompleted = Cart::where('crt_completed',0)->update([
'crt_completed' => 1,
'crt_changed' => 1,
]);
$nums = count($uncompleted);

Session::flash('carts-updated',$nums);

return redirect()->back();
}

Now I simply run an update query and then I wanted to show the number rows that gets affected and add it to a session so I can retrieve that in the Blade, like this:


@if(Session::has('carts-updated'))
<div class="alert alert-success" role="alert">
{{ Session::get('carts-updated') }}
rows gets updated!
</div>
@endif

But I get this error:


count(): Parameter must be an array or an object that implements Countable


Which is pointing to this line:


$nums = count($uncompleted);

So what's going wrong here? How can I fix this issue?



My Answer:
The issue is that the update method in Laravel returns the number of rows affected, not an array of the updated rows. So you cannot use count() on the result of the update method.

To fix this issue, you can simply use the $uncompleted variable directly to get the number of rows updated. Here's the updated code:

php
public function updateUncompletedCarts(Request $request)
{
$nums = Cart::where('crt_completed', 0)->update([
'crt_completed' => 1,
'crt_changed' => 1,
]);

Session::flash('carts-updated', $nums);

return redirect()->back();
}


Now, $nums will contain the number of rows updated by the update query, and you can use it to display the message in your Blade template.

Rate this post

5 of 5 based on 5099 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us