Laravel Query Builder v7: a must-have package for building APIs in Laravel original
We just released v7 of spatie/laravel-query-builder, our package that makes it easy to build flexible API endpoints. If you're building an API with Laravel, you'll almost certainly need to let consumers filter results, sort them, include relationships and select specific fields. Writing that logic by hand for every endpoint gets repetitive fast, and it's easy to accidentally expose columns or relationships you didn't intend to.
Our query builder takes care of all of that. It reads query parameters from the URL, translates them into the right Eloquent queries, and makes sure only the things you've explicitly allowed can be queried.
// GET /users?filter[name]=John&include=posts&sort=-created_at $users = QueryBuilder::for(User::class) ->allowedFilters('name') ->allowedIncludes('posts') ->allowedSorts('created_at') ->get(); // select * from users where name = 'John' order by created_at desc
This major version requires PHP 8.3+ and Laravel 12 or higher, and brings a cleaner API along with some features we've been wanting to add for a while.
Let me walk you through how the package works and what's new.
