• Stars
    star
    84
  • Rank 389,211 (Top 8 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 8 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Laravel package to filter Eloquent model records based on query parameters. Fully inspired by the Laracasts episode https://laracasts.com/series/eloquent-techniques/episodes/4

Query Filters

Author PHP Version Laravel Version Octane Compatibility Build Status Coverage Status Quality Score Latest Version Software License PSR-12 Total Downloads

SensioLabsInsight

Query Filters was fully inspired by this lesson on Laracasts, it provides a simple way to filter Eloquent models based on query parameters of an HTTP request.

Install

Via Composer:

composer require cerbero/query-filters

If your version of Laravel is prior to 5.5, you can register this package service provider by adding the following line to the list of providers in config/app.php:

'providers' => [
    ...
    Cerbero\QueryFilters\Providers\QueryFiltersServiceProvider::class,
]

This package includes a generator for query filter classes that by default are generated in app/QueryFilters. If you prefer a different path, you can set it in the config/query_filters.php file after running:

php artisan vendor:publish --tag=query_filters_config

Usage

Imagine to have a route for indexing all actors stored in the database. This route accepts query parameters to filter records, for example:

/actors?won_oscar&acting=0&acted-in=2000

In this case the route will need to display only actors who won at least one Oscar, are no longer acting but acted in 2000.

This can be achieved by generating a query filters class and optionally defining the allowed query parameters and related variable names via the following Artisan command:

php artisan make:query-filters ActorFilters 'won_oscar&acting=bool&acted-in=year'

That command will generate and populate with filters the ActorFilters class:

use Cerbero\QueryFilters\QueryFilters;

/**
 * Filter records based on query parameters.
 *
 */
class ActorFilters extends QueryFilters
{
    /**
     * Filter records based on the query parameter "won_oscar"
     * 
     * @return void
     */
    public function wonOscar()
    {
        // $this->query
    }

    /**
     * Filter records based on the query parameter "acting"
     * 
     * @param mixed $bool
     * @return void
     */
    public function acting($bool)
    {
        // $this->query
    }

    /**
     * Filter records based on the query parameter "acted-in"
     * 
     * @param mixed $year
     * @return void
     */
    public function actedIn($year)
    {
        // $this->query
    }
}

Please note how filter names are the equivalent camel case form of their related query parameters.

Filters are only applied if their query parameter is present in the HTTP request with a non-empty value, unless they need no value to function (e.g. won_oscar).

The $query property lets filters determine how queries change when they are applied:

public function wonOscar()
{
    $this->query->where('oscars', '>', 0);
}

public function acting($bool)
{
    $this->query->where('acting', $bool);
}

public function actedIn($year)
{
    $this->query->whereHas('movies', function ($movies) use ($year) {
        $movies->whereYear('release_date', '=', $year);
    });
}

After filters are defined, Eloquent models can apply them by using the FiltersRecords trait:

use Cerbero\QueryFilters\FiltersRecords;
use Illuminate\Database\Eloquent\Model;

class Actor extends Model
{
    use FiltersRecords;
}

Finally in your route you can filter actors by calling the method filterBy() of your model and passing the query filters:

use App\Actor;
use App\QueryFilters\ActorFilters;

...

public function index(ActorFilters $filters)
{
    return Actor::filterBy($filters)->get();
}

Alternatively you can hydrate query filters from a plain array:

use App\Actor;
use App\QueryFilters\ActorFilters;
use Illuminate\Http\Request;

...

public function index(Request $request)
{
    $filters = ActorFilters::hydrate($request->query());

    return Actor::filterBy($filters)->get();
}

Sometimes you may want to silently skip filters if their value is not valid. Instead of setting validation rules in HTTP requests, you may define them in the query filters class.

This avoids a failed validation to stop the filtering process and applies only valid filters while ignoring filters with values that do not pass the validation:

class ActorFilters extends QueryFilters
{
    protected function getRules()
    {
        return [
            'acting' => 'bool',
            'acted-in' => 'int|digits:4',
        ];
    }
}

Change log

Please see CHANGELOG for more information what has changed recently.

Testing

composer test

Contributing

Please see CONTRIBUTING and CONDUCT for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

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

More Repositories

1

json-parser

🧩 Zero-dependencies lazy parser to read JSON of any dimension and from any source in a memory-efficient way.
PHP
676
star
2

lazy-json

🐼 Framework-agnostic package to load JSON of any dimension and from any source into Laravel lazy collections recursively.
PHP
235
star
3

enum

🎲 Zero-dependencies PHP library to supercharge enum functionalities.
PHP
188
star
4

command-validator

Validate Laravel console commands input.
PHP
160
star
5

laravel-enum

Discontinued. Enum generator for Laravel.
PHP
136
star
6

eloquent-inspector

🕵️ Inspect Laravel Eloquent models to collect properties, relationships and more.
PHP
115
star
7

Workflow

Laravel 5 package to create extendible and maintainable apps by harnessing the power of pipelines.
PHP
109
star
8

lazy-json-pages

📜 Framework-agnostic package to load items from any paginated JSON API into a Laravel lazy collection via async HTTP requests.
PHP
82
star
9

notifiable-exception

Laravel package to send notifications when some exceptions are thrown.
PHP
76
star
10

exception-handler

Extend the Laravel exception handler to let service providers determine how custom exceptions should be handled.
PHP
60
star
11

laravel-dto

Data Transfer Object (DTO) for Laravel
PHP
55
star
12

Auth

Laravel authentication module.
PHP
49
star
13

octane-testbench

⛽ Set of utilities to test Laravel applications powered by Octane.
PHP
42
star
14

sql-dumper

Laravel package to dump SQL queries, related EXPLAIN and location in code in different formats.
PHP
23
star
15

pest-plugin-laravel-octane

⛽ Pest plugin to test Laravel applications powered by Octane.
PHP
21
star
16

json-objects

Extract objects from large JSON files, endpoints or streams while saving memory.
PHP
20
star
17

dto

Data Transfer Object (DTO).
PHP
16
star
18

Transformer

Framework agnostic package to transform objects and arrays by manipulating, casting and mapping their properties.
PHP
14
star
19

Sublime-Text-PHP-and-Laravel-Snippets

Sublime Text snippets to ease development with PHP and Laravel.
13
star
20

console-tasker

🦾 Laravel package to create lean, powerful, idempotent and beautiful Artisan commands.
PHP
10
star
21

workflow-demo

Demo for Workflow repository
CSS
9
star
22

Date

Framework agnostic and easy to use tool to work with dates.
PHP
6
star
23

start

Mac service written in Automator to run several softwares and commands by pressing a hot key.
AppleScript
2
star
24

fluent-api

Framework agnostic starting point to perform fluent calls to any API.
PHP
1
star
25

Affiliate

PHP
1
star