tobitobsen's avatar

sortByDesc('created_at') not working

This is how I get all my approved quotes and send them to an Inertia Page.

// βœ… - ok
Route::get('/browse', function () {
    return Inertia::render('Browse', ['quotes' => Quote::where('is_approved', 1)->get()->load('author')]);
});

However if I add ->sortByDesc('created_at') it stops working:

// πŸ’₯ - boom
Route::get('/browse', function () {
    return Inertia::render('Browse', ['quotes' => Quote::where('is_approved', 1)->get()->load('author')->sortByDesc('created_at')]);
});

How come? πŸ€”

If I dump & die it looks fine though..

// βœ… - ok
dd(Quote::where('is_approved', 1)->get()->load('author')->sortByDesc('created_at'));
0 likes
4 replies
Niush's avatar

The sortByDesc in your code is a Laravel collections function. You should be sorting before calling the get() function, like below. So that it sorts in database level. And, you can also use with() for eager loading author relation.

 Quote::where('is_approved', 1)->latest('created_at')->with('author')->get();

Probably the reason it breaks your code is you needed to do values()->all() as shown in the documentation.

1 like
tobitobsen's avatar

Thanks @niush!

Your snippet did not quite work, but you pointed me in the right direction. After some trying I came up with ..

Quote::where('is_approved', 1)->with('author')->get()->sortByDesc('created_at')->values()->all()

.. which is working.

Snapey's avatar
Snapey
Best Answer
Level 122

@tobitobsen you are still sorting in memory, not in the database query.

Quote::where('is_approved', 1)->with('author')->orderBy('created_at', 'desc')->get();

Note eloquent uses orderBy not sortBy

2 likes

Please or to participate in this conversation.