Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

selcukgiray's avatar

How to handle sorting, pagination, and limit in a Laravel REST API?

I’m building a REST API with Laravel and I want to manage query parameters like sorting, pagination, and limit in a clean and reusable way.

For example:

Sorting results by a field (e.g., ?sort=created_at&order=desc)

Limiting the number of returned items (e.g., ?limit=10)

Paginating responses properly (e.g., ?page=2&per_page=15)

What is the recommended approach or best practice to implement this in Laravel? Should I use a package, write custom query logic, or rely on built-in features like paginate()?

0 likes
2 replies
martinbean's avatar

@selcukgiray You can use Spatie’s query builder package in tandem with Laravel’s built-in API resources:

public function index()
{
    $articles = QueryBuilder::for(Article::query())
        ->allowedFilters([
            // Put allowed filters here..
        ])
        ->allowedSorts([
            // Put allowed sorts here...
        ])
        ->paginate();

    return ArticleResource::collection($articles);
}
1 like

Please or to participate in this conversation.