Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eloquent laravel: How to get a row count from a ->get()

I'm having a lot of trouble figuring out how to use this collection to count rows.

$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)                 ->get(); 

I have tried adding->count() but didn't work. I have tried doing count($wordlist). I'm not really sure what to do without needing a second request as a->count() method.

like image 786
JP Foster Avatar asked Nov 12 '15 16:11

JP Foster


People also ask

How do I count items in Laravel?

$shops = Shop::where('user_id', Auth::user()->id)->byRating(); $p = $shops->where('status', 0)->count(); $a = $shops->where('status', 1)->count(); $d = $shops->where('status', 2)->count(); $shops = $shops->paginate(10); return view('home', compact('shops', 'p', 'a', 'd'));

What is count in Laravel?

count is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array: $wordCount = count($wordlist); If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count method.


1 Answers

Answer has been updated

count is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array:

$wordCount = count($wordlist); 

If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count method. Example:

$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get(); $wordCount = $wordlist->count(); 

There is/was a discussion on having the query builder return a collection here: https://github.com/laravel/framework/issues/10478

However as of now, the query builder always returns an array.

Edit: As linked above, the query builder now returns a collection (not an array). As a result, what JP Foster was trying to do initially will work:

$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)             ->get(); $wordCount = $wordlist->count(); 

However, as indicated by Leon in the comments, if all you want is the count, then querying for it directly is much faster than fetching an entire collection and then getting the count. In other words, you can do this:

// Query builder $wordCount = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)             ->count();  // Eloquent $wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count(); 
like image 193
Thomas Kim Avatar answered Sep 30 '22 19:09

Thomas Kim