Laravel orderBy date is not working when using paginator

ε祈祈猫儿з 提交于 2019-12-12 03:43:42

问题


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'));
    }

回答1:


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) ]);
}


来源:https://stackoverflow.com/questions/39174377/laravel-orderby-date-is-not-working-when-using-paginator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!