Convert Figma logo to code with AI

spatie logolaravel-query-builder

Easily build Eloquent queries from API requests

4,017
395
4,017
10

Top Related Projects

3,432

Laravel Eloquent roles and abilities.

Record the change log from models in Laravel

Debugbar for Laravel (Integrates PHP Debug Bar)

Associate users with roles and permissions

jQuery DataTables API for Laravel

1,539

Laravel Scout provides a driver based solution to searching your Eloquent models.

Quick Overview

Laravel Query Builder is a package that allows you to filter, sort, and include eloquent relations based on a request. It provides an easy-to-use API for building dynamic database queries from incoming HTTP requests, making it ideal for building flexible and powerful APIs.

Pros

  • Simplifies the process of creating dynamic queries based on user input
  • Integrates seamlessly with Laravel's Eloquent ORM
  • Provides a clean and expressive syntax for defining allowed filters, sorts, and includes
  • Enhances API flexibility without compromising security

Cons

  • May introduce a learning curve for developers new to the concept
  • Could potentially lead to performance issues if not used carefully with large datasets
  • Requires careful configuration to prevent exposing sensitive data or allowing unintended queries
  • May not be suitable for all types of applications, especially those with very specific or complex query requirements

Code Examples

  1. Basic usage:
use Spatie\QueryBuilder\QueryBuilder;

$users = QueryBuilder::for(User::class)
    ->allowedFilters(['name', 'email'])
    ->allowedSorts(['name', 'created_at'])
    ->get();

This example creates a query builder for the User model, allowing filtering by name and email, and sorting by name and creation date.

  1. Including relations:
$posts = QueryBuilder::for(Post::class)
    ->allowedIncludes(['author', 'comments'])
    ->get();

This code allows including the author and comments relations when querying posts.

  1. Custom filters:
use Spatie\QueryBuilder\AllowedFilter;

$users = QueryBuilder::for(User::class)
    ->allowedFilters([
        AllowedFilter::callback('age_range', function ($query, $value) {
            $query->whereBetween('age', [$value['min'], $value['max']]);
        }),
    ])
    ->get();

This example demonstrates a custom filter for querying users within a specific age range.

Getting Started

  1. Install the package via Composer:

    composer require spatie/laravel-query-builder
    
  2. Use the QueryBuilder in your controller:

use Spatie\QueryBuilder\QueryBuilder;

class UserController extends Controller
{
    public function index()
    {
        $users = QueryBuilder::for(User::class)
            ->allowedFilters(['name', 'email'])
            ->allowedSorts(['name', 'created_at'])
            ->get();

        return response()->json($users);
    }
}
  1. Make API requests with query parameters:
    GET /users?filter[name]=John&sort=-created_at
    

This will return users named John, sorted by creation date in descending order.

Competitor Comparisons

3,432

Laravel Eloquent roles and abilities.

Pros of Bouncer

  • Focuses on role-based access control (RBAC) and permissions management
  • Provides a fluent API for defining and checking permissions
  • Offers advanced features like ability inheritance and caching

Cons of Bouncer

  • Limited to authorization and doesn't handle query building
  • May require more setup for complex permission structures
  • Less flexibility for filtering and sorting data

Code Comparison

Bouncer:

Bouncer::allow('admin')->to('edit', Post::class);
Bouncer::allow('editor')->to('create', Post::class);

if ($user->can('edit', $post)) {
    // User can edit the post
}

Laravel Query Builder:

$posts = QueryBuilder::for(Post::class)
    ->allowedFilters(['title', 'content'])
    ->allowedSorts(['created_at', 'title'])
    ->paginate();

While Bouncer excels in managing permissions and roles, Laravel Query Builder is designed for building dynamic queries based on request parameters. Bouncer is ideal for implementing complex authorization systems, whereas Laravel Query Builder simplifies the process of creating filterable, sortable, and paginated API endpoints. The choice between the two depends on the specific needs of your project: authorization management or flexible query building.

Record the change log from models in Laravel

Pros of Laravel Auditing

  • Specialized in tracking model changes and creating audit logs
  • Provides detailed audit trails with customizable storage options
  • Offers event-driven auditing with support for custom audit drivers

Cons of Laravel Auditing

  • Limited to auditing functionality, not a general-purpose query builder
  • May have a steeper learning curve for implementing complex auditing scenarios
  • Potential performance impact when auditing large-scale operations

Code Comparison

Laravel Auditing:

use OwenIt\Auditing\Contracts\Auditable;

class User extends Model implements Auditable
{
    use \OwenIt\Auditing\Auditable;
}

Laravel Query Builder:

use Spatie\QueryBuilder\QueryBuilder;

$users = QueryBuilder::for(User::class)
    ->allowedFilters(['name', 'email'])
    ->allowedSorts(['name', 'created_at'])
    ->get();

Summary

Laravel Auditing focuses on creating detailed audit logs for model changes, offering specialized functionality for tracking data modifications. It excels in providing comprehensive audit trails but is limited to this specific use case. On the other hand, Laravel Query Builder is a more general-purpose tool for building dynamic queries based on request parameters, offering greater flexibility for various querying scenarios but lacking the specialized auditing features of Laravel Auditing.

Debugbar for Laravel (Integrates PHP Debug Bar)

Pros of Laravel Debugbar

  • Provides comprehensive debugging information, including queries, exceptions, and performance metrics
  • Offers a user-friendly interface for inspecting application data during development
  • Integrates seamlessly with Laravel, providing insights into the framework's internals

Cons of Laravel Debugbar

  • Primarily focused on debugging and development, not query building or API filtering
  • May impact performance if left enabled in production environments
  • Requires manual configuration for certain advanced features

Code Comparison

Laravel Debugbar:

use Barryvdh\Debugbar\Facade as Debugbar;

Debugbar::info($object);
Debugbar::error('Error!');
Debugbar::warning('Watch out…');
Debugbar::addMessage('Another message', 'mylabel');

Laravel Query Builder:

use Spatie\QueryBuilder\QueryBuilder;

$users = QueryBuilder::for(User::class)
    ->allowedFilters(['name', 'email'])
    ->allowedSorts(['name', 'created_at'])
    ->paginate();

While Laravel Debugbar excels in providing detailed debugging information during development, Laravel Query Builder focuses on simplifying the creation of complex database queries and API filtering. Laravel Debugbar is more suited for development and troubleshooting, whereas Laravel Query Builder is designed to enhance production code by offering a clean, fluent interface for building queries based on request parameters.

Associate users with roles and permissions

Pros of laravel-permission

  • Provides a robust and flexible role-based access control system
  • Offers caching mechanisms for improved performance
  • Supports multiple user models and guard types

Cons of laravel-permission

  • More complex setup and configuration compared to laravel-query-builder
  • Limited to handling permissions and roles, not general query building
  • May require additional customization for complex authorization scenarios

Code Comparison

laravel-permission:

$user->assignRole('writer');
$user->hasPermissionTo('edit articles');

laravel-query-builder:

QueryBuilder::for(User::class)
    ->allowedFilters(['name', 'email'])
    ->allowedSorts(['name', 'created_at'])
    ->get();

Summary

laravel-permission is focused on managing user roles and permissions, providing a comprehensive solution for access control in Laravel applications. It excels in handling complex authorization scenarios but requires more setup.

laravel-query-builder, on the other hand, is designed for building dynamic queries based on request parameters. It offers a simpler approach to filtering, sorting, and including relations in API responses.

While both packages serve different purposes, they can be used together in a Laravel application to create a powerful and flexible backend system. laravel-permission handles user access control, while laravel-query-builder simplifies API query construction.

jQuery DataTables API for Laravel

Pros of Laravel DataTables

  • Built-in support for server-side processing, ideal for large datasets
  • Extensive customization options for DataTables, including styling and plugins
  • Seamless integration with jQuery DataTables library

Cons of Laravel DataTables

  • Tightly coupled with jQuery DataTables, limiting flexibility for other front-end frameworks
  • Steeper learning curve due to more complex API and configuration options
  • May introduce unnecessary overhead for simpler use cases

Code Comparison

Laravel DataTables:

return DataTables::of(User::query())
    ->addColumn('action', function ($user) {
        return '<a href="#">Edit</a>';
    })
    ->make(true);

Laravel Query Builder:

return QueryBuilder::for(User::class)
    ->allowedFilters(['name', 'email'])
    ->allowedSorts(['name', 'created_at'])
    ->get();

Laravel Query Builder focuses on building API-friendly queries with a clean, fluent interface, while Laravel DataTables specializes in creating feature-rich, interactive tables with server-side processing. The choice between the two depends on your specific project requirements, front-end technology stack, and the complexity of your data presentation needs.

1,539

Laravel Scout provides a driver based solution to searching your Eloquent models.

Pros of Scout

  • Built-in support for full-text search engines like Algolia and MeiliSearch
  • Seamless integration with Laravel's Eloquent ORM
  • Automatic indexing and syncing of model changes

Cons of Scout

  • Limited to search functionality, not a general-purpose query builder
  • Requires additional setup and configuration for search engines
  • May introduce additional complexity for simple search scenarios

Code Comparison

Scout:

use Laravel\Scout\Searchable;

class Post extends Model
{
    use Searchable;
}

$results = Post::search('Laravel')->get();

Laravel Query Builder:

use Spatie\QueryBuilder\QueryBuilder;

$results = QueryBuilder::for(Post::class)
    ->allowedFilters(['title', 'content'])
    ->get();

Key Differences

  • Scout focuses on full-text search capabilities, while Laravel Query Builder provides a more general-purpose query building solution
  • Scout requires integration with external search engines, whereas Laravel Query Builder works directly with the database
  • Laravel Query Builder offers more flexibility in constructing complex queries and filtering options

Use Cases

Scout is ideal for applications requiring advanced search functionality, especially when dealing with large datasets or complex text-based searches. Laravel Query Builder is better suited for building dynamic, filterable APIs and handling complex query requirements without the need for full-text search capabilities.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Build Eloquent queries from API requests

Latest Version on Packagist Test Status Code Style Status Total Downloads

This package allows you to filter, sort and include eloquent relations based on a request. The QueryBuilder used in this package extends Laravel's default Eloquent builder. This means all your favorite methods and macros are still available. Query parameter names follow the JSON API specification as closely as possible.

Basic usage

Filter a query based on a request: /users?filter[name]=John:

use Spatie\QueryBuilder\QueryBuilder;

$users = QueryBuilder::for(User::class)
    ->allowedFilters('name')
    ->get();

// all `User`s that contain the string "John" in their name

Read more about filtering features like: partial filters, exact filters, scope filters, custom filters, ignored values, default filter values, ...

Including relations based on a request: /users?include=posts:

$users = QueryBuilder::for(User::class)
    ->allowedIncludes('posts')
    ->get();

// all `User`s with their `posts` loaded

Read more about include features like: including nested relationships, including relationship count, custom includes, ...

Sorting a query based on a request: /users?sort=id:

$users = QueryBuilder::for(User::class)
    ->allowedSorts('id')
    ->get();

// all `User`s sorted by ascending id

Read more about sorting features like: custom sorts, sort direction, ...

Works together nicely with existing queries:

$query = User::where('active', true);

$userQuery = QueryBuilder::for($query) // start from an existing Builder instance
    ->withTrashed() // use your existing scopes
    ->allowedIncludes('posts', 'permissions')
    ->where('score', '>', 42); // chain on any of Laravel's query builder methods

Selecting fields for a query: /users?fields[users]=id,email

$users = QueryBuilder::for(User::class)
    ->allowedFields(['id', 'email'])
    ->get();

// the fetched `User`s will only have their id & email set

Read more about selecting fields.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-query-builder

Read the installation notes on the docs site: https://spatie.be/docs/laravel-query-builder/v5/installation-setup.

Documentation

You can find the documentation on https://spatie.be/docs/laravel-query-builder/v5.

Find yourself stuck using the package? Found a bug? Do you have general questions or suggestions for improving the media library? Feel free to create an issue on GitHub, we'll try to address it as soon as possible.

If you've found a bug regarding security please mail security@spatie.be instead of using the issue tracker.

Upgrading

Please see UPGRADING.md for details.

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail security@spatie.be instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.