Search code examples
phplaravellaravel-5.3

Laravel orderBy date is not working when using paginator


I am new to laravel and am struggling to figure this one out.I am trying to order my posts by date and also use the paginator. Whenever I remove the paginator. it orders by date, but adding it back in orders by id, I think?

My model

class Post extends Model
{
    //

protected $dates = ['date'];
}

My controller method

public function show()
    {

        $posts = Post::orderBy('date','desc')->get();


        return view('welcome',['posts' => Post::paginate(5)], compact('posts'));
    }

Solution

  • You're essentially retrieving all posts and then paginating them, after retrieving all posts and ordering them.

    Your code breaks down like this:

    public function show()
    {
    
        // retrieve posts and order them by date
        $posts = Post::orderBy('date','desc')->get();
    
        // retrieve posts again and paginate them
        return view('welcome',['posts' => Post::paginate(5)], compact('posts'));
    }
    

    You have two options --

    Get posts, order them, paginate them, and store them in a variable that you pass to your view:

    public function show()
    {
    
        $posts = Post::orderBy('date','desc')->paginate(5);
    
    
        return view('welcome', compact('posts'));
    }
    

    Or get the posts, order them and paginate them while passing them to the view:

    public function show()
    {
    
        return view('welcome',[ 'posts' => Post::orderBy('date','desc')->paginate(5) ]);
    }