Home » Php » counting the amount of rows returned with a query in laravel

counting the amount of rows returned with a query in laravel

Posted by: admin October 29, 2017 Leave a comment

Questions:

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!

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.

Questions:
Answers:

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

echo count($check_friend_request);

Questions:
Answers:

If you use a paginator:

$check_friend_request->total();

If you don’t use a paginator:

count($check_friend_request);

See documentation at https://laravel.com/docs/5.3/pagination

Questions:
Answers:

Try this one hope it will help for you.

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