Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Laravel - OrderBy (reverse) and paginate

I am trying everything for an hour to do a simple thing in laravel, and nothing works....

So, I have lots of episodes which should be paginated, but before that those episodes should be orderedBy a has-to-many relationship.

I've tried this, but it didn't work:

$result = TheEpisode::where('seriesID', $id)->with(['TheNumbers' => function ($query) {
  return $query->orderBy('episodeNumber', 'desc')->get();
}])->paginate(12);

I also tried this:

$result = TheEpisode::where('seriesID', $id)->orderBy("TheNumbers.episodeNumber", 'desc')->paginate(12);

Does not work either.

EDIT

$result = TheEpisode::where('seriesID', $id)->get()->sortByDesc(function ($item) {
  return $item->TheNumbers->max('episodeNumber');
});

This works, and returns 120 episodes in reverse order, now what I need is to paginate it, how do I do that?

like image 642
Coder Avatar asked Feb 03 '26 10:02

Coder


1 Answers

Try:

$result = TheEpisode::where('seriesID', $id)->sortByDesc(function ($item) {
    return $item->TheNumbers->max('episodeNumber');
})->paginate(15)->get();

https://laravel.com/docs/5.3/pagination

like image 98
Serg Chernata Avatar answered Feb 06 '26 02:02

Serg Chernata



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!