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.
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();
Direct get a count of row
Using Eloquent
//Useing Eloquent
$count = Model::count();
//example
$count1 = Wordlist::count();
Using query builder
//Using query builder
$count = \DB::table('table_name')->count();
//example
$count2 = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)->count();
Its better to access the count with the laravels count method
$count = Model::where('status','=','1')->count();
or
$count = Model::count();
also, you can fetch all data and count in the blade file.
for example:
your code in the controller
$posts = Post::all();
return view('post', compact('posts'));
your code in the blade file.
{{ $posts->count() }}
finally, you can see the total of your posts.
//controller $count = Post::count(); return view('post', compact('count'));
//blade {{$count}}
or
//controller $posts = Post::all(); return view('post', compact('posts'));
//blade{{count($posts)}}
Related
Laravel version 4.2
I'm having issues with this one problem I have.
I need to fill a quota of 5 results however I only have an array size of 3. I also need the rows to be selected randomly from the Array.
*edit: Fetching all results is not feasible
$store_id_array = array('111', '222' , '333');
$reviews = Review::whereIn('store_id', $store_id_array)
->take(5)
->get();
return Response::json($reviews);
This will return 5 results however only from the first item in the array.
How do I select randomly from the array items?
For Laravel below version 5:
orderBy(DB::raw('RAND()')) like this:
$reviews = Review::whereIn('store_id', $store_id_array)
->orderBy(DB::raw('RAND()'))
->take(5)
->get();
For Laravel 5.0 +
use inRandomOrder() method:
$reviews = Review::whereIn('store_id', $store_id_array)
->inRandomOrder()
->take(5)
->get();
public function index()
{
$categories = Category::latest()->get();
$protfolios = Protfolio::all();
$randompost = Post::approved()->publish()->take(4)->InRandomOrder()->get();
$allposts = Post::where('price', 0)->approved()->publish()->take(8)->get();
$posts = Post::latest()->where('price', '>=', 0)->approved()->publish()->take(8)->get();
$latestposts = Post::latest()->approved()->publish()->take(8)->get();
return view('welcome',compact('posts','randompost ','categories','allposts','latestposts','protfolios'));
}
I have code like this
$tag = Tag::where('slug' = $slug)->first();
$posts = $tag->posts;
It works correctly but I want to use limit, orderBy, offset and other operation on posts. So it works
$posts = $tag->posts->where('accept', 1);
But it doesn't works
$posts-> $tag->posts->orderBy('created_at', 'desc');
//or
$posts-> $tag->posts
->offset($offset)
->limit($limit);
I must use offset and limit into query from var.
How I can do that?
When you set up your initial query Tag::where('slug' = $slug)->first(); you're using Query Builder and it's methods. But when Laravel returns the results, they're returned as a collction object -- those have very similar but slightly different methods available. https://laravel.com/docs/5.8/collections#available-methods
On a collection or its children, instead of orderBy() you would use sortBy() or sortByDesc(). Those will return an instance of the collection, sorted by your specified key. $results = $posts->sortBy($sorting);
The same idea with limit, in this case you can use the splice method. (Collections are basically php arrays on steroids) Splice accepts two parameters, a starting index and a limit. So, to get only the first 10 items, you could do this: $results = $posts->splice(0, 10);
And of course, you can also chain those togeather as $results = $tag->posts->sortBy('id')->splice(0, 10);
When you use child, Eloquent create another subquery, then result is added to parent, thats way its not sorting properly.
A solution could be join tables:
$tags = Tag::where('tags.slug' = $slug)
->join('tags', 'tag.post_id', '=', 'posts.id')
->orderBy('posts.created_at', 'desc')
->select('tags.*')
->get();
I am using Eloquent ORM outside of Laravel-4 and I am building a custom Paginator.
First, I build a query using Fluent Query Builder. I want to get the number of result the query could return using count() and then I do a custom pagination using take(x) and skip(y). I need to do the count() before the take()->skip()->get() so I dont fall outside of the page range. The problem is that when I use the count() method on the query, it seems to remove any select I added previously.
I isolated the problem to this simple example:
$query = DB::table('companies')
->join('countries','companies.country_id','=','countries.id')
->select(
'companies.name as company_name',
'countries.name as country_name'
);
$nbPages = $query->count();
$results = $query->get();
//$results contains all fields of both tables 'companies' and 'countries'
If i invert the order of the count and get, it works fine:
$results = $query->get();
$nbPages = $query->count();
//$results contains only 'company_name' and 'country_name'
Question: is there a more elegant way the using something like this:
$tmp = clone $query;
$nbPages = $tmp->count();
$results = $query->get();
There is not, unfortunately. Open issue on github about the problem: https://github.com/laravel/framework/pull/3416
How to merge this two queries ?
$data = DB::table('category_to_news')
->where('category_to_news.name', ucwords($category))
->remember(1440)
->count();
and
$data = DB::table('category_to_news')
->where('category_to_news.name', ucwords($category))
->remember(1440)
->get();
So, as far as I understand from your comment, you simply want to get all records from the table category_to_news and you want to know how many records are in there, right?
MySQL's count is an aggregate functions, which means: It takes a set of values, performs a calculation and returns a single value. If you put it into your names-query, you get the same value in each record. I'm not sure if that has anything to do with 'optimization'.
As already said, you simply run your query as usual:
$data = DB::table('category_to_news')
->where('name', ucwords($category))
->remember(1440)
->get(['title']);
$data is now of type Illuminate\Support\Collection which provides handy functions for collections, and one them is count() (not to be confused with the above mentioned aggregate function - you're back in PHP again, not MySQL).
So $data->count() gives you the number of items in the collection (which pretty much is an array on steroids) without even hitting the database.
Hi DB class dont return collection object it give error "call member function on array" but eloquent return collection object. for above code we can use collect helper function to make it collection instance then use count and other collection methods https://laravel.com/docs/5.1/collections#available-methods .
$data = DB::table('category_to_news')
->where('name', ucwords($category))
->remember(1440)
->get();
$data = collect($data);
$data->count();
You my get it using:
$data = DB::table('category_to_news')
->where('name', ucwords($category))
->remember(1440)
->get();
To get the count, try this:
$data->count();
Why you are using DB::table(...), instead you may use Eloquent model like this, create the model in your models directory:
class CategoryToNews extends Eloquent {
protected $table = 'category_to_news';
protected $primaryKey = 'id'; // if different than id then change it here
}
Now, you may easily use:
$data = CategoryToNews::whereName(ucwords($category))->get();
To get the count, use:
$data->count();
In laravel, I know you can do
$users = Post::where('hide', '=', 0)->take(40)->get();
to get all Post-objects where hide = 0 and
$users = Post::orderBy('created_at', 'DESC')->take(20)->get();
to sort them, but what if I want to do both?
You should be able to do
$users = Post::where('hide', '=', 0)->orderBy('created_at', 'desc')->take(20)->get();
You can continue to chain methods from the query builder after the where.