strangequirks's avatar

How to get the latest item by id.

I am trying to do get all the latest items and sort by id descending (i.e. get all items that were just added with a limit and offset).

This is my code-

$products = Product::all()
                ->slice($request->get('offset'))
                ->take($request->get('limit'))
                ->sortByDesc('id')
                ->toBase();

However it seems when I have more that that limit, then I dont have the right order. It gets me say 10 products but not sorted corrected. Any idea how to do this?

1 like
2 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

Try this-

$products = Product::skip(10)
    ->take($request->input('limit'))
    ->orderBy('id', 'desc')
    ->get();

You can use the value in skip() from request also. Like this way skip($request->input('offset')).

3 likes
rossiluca's avatar

This way will keep the existing index order. Try this instead: ->sortByDesc('id')->values()

2 likes

Please or to participate in this conversation.