Sredny M Casanova Sredny M Casanova - 1 year ago 86
PHP Question

retrieve records from laravel model

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:


But is the same. So then, I just put:


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?

Answer Source

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 }}

{{ $models->links() }}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download