Reputation: 5063
I have a Laravel application, I have a database table with 780950 registers, so, when I retrieve this with eloquent it takes a long long time and then gives time exceeded error. Is there a way to retrieve for example the first 30 records? I tried with this:
mymodel::all()->take(30)->get();
But is the same. So then, I just put:
mymodel::where('id','<','30')->get();
And it works, but it's not what I want because I want to paginate and display all the records. So, I know that it's a lot of records, but if I can retrieve the first 30 and then with ajax retrieve another 30 more. So what is the best and more elegant way to achieve this in Laravel 5.3?
Upvotes: 0
Views: 996
Reputation: 953
When you do Model::all()->take(30)->get();
, you're actually saying "retrieve all of the database records, then give me the first 30". So you'll be loading all 800,000 records just to grab the first 30.
What you actually want to do, if you want pagination, is:
$models = Model::paginate($perPage);
The paginate()
method will automatically determine the current page from the query strings in the URL, and give you back an object that you can pass to your views to paginate.
<div class="container">
@foreach ($models as $model)
{{ $model->name }}
@endforeach
</div>
{{ $models->links() }}
Upvotes: 2
Reputation: 163978
You can use skip()
and take()
:
mymodel::skip(0)->take(30)->get();
Another way is getting data by chunks with chunk()
:
mymodel::chunk(200, function ($flights) {
foreach ($flights as $flight) {
//
}
});
Upvotes: 2