Search code examples
laraveleloquentlumen

Eloquent ORM get latest items query


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).

So I did this:

$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 with Eloquent ORM?


Solution

  • You are probably intending to have the database handle the offset and skipping and ordering instead of pulling all the possible records then taking only what you want, then sorting them ... if you were going to do it your way you would need to sort before you skip and take, by the way.

    Using the database to the the filtering and ordering:

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