mitismirza's avatar

laravel heavy pagination

hi i put 1 million record in database and paginate it with any relation :

    public function index(){
        $phones = Phone::latest()->paginate(10);
        return view('phones' , compact('phones') );
    }

and show it in blade:


                <tbody>
                @foreach($phones as $phone)
                    <tr style="max-width: 1024px;">
                        <th scope="row">{{ $phone->id }}</th>
                        <th scope="row">{{ $phone->name }}</th>
                        <th scope="row">{{ $phone->price }}</th>
                        <th scope="row">{{ $phone->date }}</th>
                        <th scope="row">{{ $phone->created_at }}</th>
                        <th scope="row">{{ $phone->updated_at }}</th>
                    </tr>
                @endforeach
                </tbody>
            </table>
            <div style="text-align:center;">
                {{ $phones->links() }}
            </div>

it paginate it and show pagination as well , but the problem is when i want paginate to latest pages it will show the page with 40 second delay!

but https://www.adminer.org/ have one page php that can connect very simply to database and retrieve one trillion and its last pages in 1 second!

what i should to do to take down the delay time to 1 second?

0 likes
3 replies
mortezapiri's avatar

you can cache it , and Receive data from cache .

1 like
Cronix's avatar
Cronix
Best Answer
Level 67

for that particular query, I'd put an index on the created_at field. It has to scan the entire table from first record to last record, just to find the "latest" records, which are at the end. The more rows, the longer that takes. An index will speed that up quite a bit.

$phones = Phone::latest()->paginate(10);

The created_at field is what latest() is sorting on, in desc order. By default laravel doesn't index the created_at/updated_at fields. Anything you join on, order by, group by should have an index.

That should speed it up quite a bit. Another thing you could do if that isn't fast enough, is caching the queries so it doesn't even hit the db.

1 like

Please or to participate in this conversation.