Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

CedricBongaerts's avatar

Combining Paginate with OrderBy

I'm trying to make a posts view to by paginated (which I have been able to do) using this code:

index.blade.php

@extends('masterpage.app')

@section('content')
        @foreach (array_chunk($posts->all(), 2) as $row)
            <div class="row">
                @foreach ($row as $post)
                    <article class="col-md-6">
                        <h3>{!! link_to_route('post.show', $post->title, [$post->slug]) !!} <small> - by {{ $post->user->username }}</small></h4>
                        <h5>{!! str_limit($post->content, $limit = 200, $end = '...') !!}</h4>
                    </article>
                @endforeach
            </div>
        @endforeach
@stop

PostsController.php

public function index(Post $post)
    {
        $posts = Post::paginate(6);
        return view('posts.index', compact('posts'));
    }

Now at first I had $posts = Post::orderBy('created_at', 'desc'); but after adding the pagination, I had to leave this out due to it giving an error.

Does anyone know a way to combine these two, so that my posts are desc but also have the paginate?

Thanks

0 likes
4 replies
pmall's avatar
pmall
Best Answer
Level 56

Doesn't this work ?

$posts = Post::orderBy('created_at', 'desc')->paginate(6);
8 likes
COTIGA's avatar

@PMALL - You can use "id" instead "created_at", the classment will be the same and the request will optimised

Please or to participate in this conversation.