Home > Net >  How to count number of rows that gets updated
How to count number of rows that gets updated

Time:03-15

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  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?

CodePudding user response:

As per the documentation : https://laravel.com/docs/4.2/eloquent#insert-update-delete

The update() method returns the number of affected rows.

So, your code should be :

public function updateUncompletedCarts(Request $request) {

  $uncompleted = Cart::where('crt_completed',0)->update([
    'crt_completed' => 1,
    'crt_changed' => 1,
  ]);  
   
  Session::flash('carts-updated',$uncompleted);
        
  return redirect()->back();
}
  • Related