Object of class Illuminate\Support\Collection could not be converted to int in Laravel 8

Viewed 124

I am trying to compare the two values from two tables and output the results if the values match.

$id = Auth::user()->id;
$user_id = DB::table('orders')->select('user_id')->get();
if ($id == $user_id) 
{
    $data = Order::All();
}
else
{
    return view('dashboard');
}
return view('profile.list',compact('data'));

But I am getting this error

ErrorException Object of class Illuminate\Support\Collection could not be converted to int

1 Answers

get() returns a collection instance containing every matching record from the table. You're comparing that to an integer which is throwing the exception. What your code should be doing is something like this:

// Get all orders matching the user's id. 
$data = Order::where('user_id', Auth::user()->id)->get();

// return the data if we found any orders,
// otherwise show the dashboard.
return !empty($data) ? 
    view('profile.list',compact('data')) : 
    view('dashboard');
Related