Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

counting the amount of rows returned with a query in laravel

I appear to have hit a halt with my website, I'm trying to get the number of rows returned by the database but it doesn't seem to want to play ball... can anybody else see the problem?

This is my query:

$check_friend_request = DB::table("friend_requests")
->where("request_sent_by_id", Auth::user()->user_id && "request_sent_to_id", $curUserID[1]);

and this is how I'm "attempting" to count the number of rows

$cfr = count($check_friend_request);

whenever I try to echo $cfr it returns 1 but should return 0 because a friend request hasn't been sent. I've more than likely missed something completely obvious, but any help would be fantastic! thank you!

like image 517
Daniel Morgan Avatar asked Sep 26 '13 21:09

Daniel Morgan


2 Answers

You have following code

$check_friend_request = DB::table("friend_requests")
->where("request_sent_by_id", Auth::user()->user_id && "request_sent_to_id", $curUserID[1]);

It should be

$check_friend_request = DB::table("friend_requests")
->where("request_sent_by_id", "=", Auth::user()->user_id) // "=" is optional
->where("request_sent_to_id", "=",  $curUserID[1]) // "=" is optional
->get();

Then, you can use

if($check_friend_request){
    //...
}

Also, count($check_friend_request) will work because it returns an array of objects. read more about Query Builder on Laravel Website.

like image 90
The Alpha Avatar answered Oct 03 '22 01:10

The Alpha


To count returned result from array in Laravel, just use simple count for array i.e.

echo count($check_friend_request);
like image 20
Rakesh Kumar Avatar answered Oct 03 '22 00:10

Rakesh Kumar