All Projects → LaravelLegends → eloquent-filter

LaravelLegends / eloquent-filter

Licence: MIT license
Library to form search criteria through expressions in the query string

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to eloquent-filter

eloquent-mongodb-repository
Eloquent MongoDB Repository Implementation
Stars: ✭ 18 (-21.74%)
Mutual labels:  eloquent, filter
laravel-searchzy
Package que te permite buscar y filtrar registros de Eloquent Models en Laravel de una manera simple y sencilla.
Stars: ✭ 15 (-34.78%)
Mutual labels:  eloquent, filter
pimpable
No description or website provided.
Stars: ✭ 102 (+343.48%)
Mutual labels:  eloquent, filter
Eloquent Filter
This simple package helps you filter Eloquent data using query filters.
Stars: ✭ 24 (+4.35%)
Mutual labels:  eloquent, filter
Lara Eye
Filter your Query\Builder using a structured query language
Stars: ✭ 39 (+69.57%)
Mutual labels:  eloquent, filter
Searchable
Search/filter functionality for Laravel's Eloquent models
Stars: ✭ 113 (+391.3%)
Mutual labels:  eloquent, filter
Eloquentfilter
An Eloquent Way To Filter Laravel Models And Their Relationships
Stars: ✭ 1,113 (+4739.13%)
Mutual labels:  eloquent, filter
Sieve
A simple, clean and elegant way to filter Eloquent models.
Stars: ✭ 123 (+434.78%)
Mutual labels:  eloquent, filter
eloquent-filemaker
A Model extension and Eloquent driver for Laravel connecting to FileMaker through the Data API
Stars: ✭ 38 (+65.22%)
Mutual labels:  eloquent
plug
A collection of pluggable traits for Eloquent (Laravel) models
Stars: ✭ 13 (-43.48%)
Mutual labels:  eloquent
esa-httpclient
An asynchronous event-driven HTTP client based on netty.
Stars: ✭ 82 (+256.52%)
Mutual labels:  filter
scotty
java proxy
Stars: ✭ 44 (+91.3%)
Mutual labels:  filter
FunFilter
Freely painted area, the software will automatically add filter on its.
Stars: ✭ 15 (-34.78%)
Mutual labels:  filter
MedianFilter
A fast one-dimensional median filter algorithm
Stars: ✭ 43 (+86.96%)
Mutual labels:  filter
capella
Cloud service for image storage and delivery
Stars: ✭ 116 (+404.35%)
Mutual labels:  filter
django-admin-search
Modal filter for django admin
Stars: ✭ 60 (+160.87%)
Mutual labels:  filter
sparkar-pixelate-shader
simple script-only pixelate shader with Facebook SparkAR.
Stars: ✭ 35 (+52.17%)
Mutual labels:  filter
laravel-query-inspector
The missing laravel helper that allows you to inspect your eloquent queries with it's bind parameters
Stars: ✭ 59 (+156.52%)
Mutual labels:  eloquent
blex
Fast Bloom filter with concurrent accessibility, powered by :atomics module.
Stars: ✭ 34 (+47.83%)
Mutual labels:  filter
repository
[PHP 7] Implementation and definition of a base Repository in Domain land.
Stars: ✭ 26 (+13.04%)
Mutual labels:  filter

Laravel Legends Eloquent Filter

A useful library to make filters for Eloquent.

This library is useful to create search filters in your Rest API using the Eloquent.

🇧🇷🚀🚀🚀

Description

The Eloquent Filter library can be used to create patterns for search criterias on models in your Laravel Project. The idea is aggregate filters simply passing the values in your request payload.

Instalation

For instalation, you should be use Composer. Run the follow command:

composer require laravellegends/eloquent-filter

Usage guide

The LaravelLegends\EloquentFilter\Concerns\HasFilter trait can be used in models that will be apply the search filters.

use LaravelLegends\EloquentFilter\Concerns\HasFilter;

class User extends Model
{
    use HasFilter;
}

The HasFilter trait provides the filter and withFilter methods.

A simple way to use this library in your Laravel application is calling the filter method before get results of your model.

Example:

class UsersController extends Controller 
{
    use App\Models\User;
    
    public function index()
    {
        return User::filter()->paginate();
    }

    // or

    public function index()
    {
        return User::latest('id')->filter()->paginate();
    }

    // or

    public function index(Request $request)
    {
        return User::filter($request)->paginate();
    }
}

You can show the results when call /api/users?exact[id]=1. The sql query "select * from users where (id = 1)" will be applied.

Note: Show the rules session to more information.

Another way, is using the specific filter for a model. You can inherit the ModelFilter class to create a custom filter for a model.

For create this class, you should be use the command php artisan make:filter, as follow example:

$ php artisan make:filter UserFilter

The above command will be generate the follow class:

namespace App\Filters;

use LaravelLegends\EloquentFilter\Filters\ModelFilter;

class UserFilter extends ModelFilter 
{
    public function getFilterables(): array
    {
        return [
            'role_id' => 'not_equal', // or ['not_equal']
            'name'    => ['contains', 'starts_with'],
        ];
    }
}

In Controller

use App\Models\User;
use Illuminate\Http\Request;
use LaravelLegends\EloquentFilter\Filter;

class UsersController extends Controller
{
    // api/users?starts_with[name]=Wallace&not_equal[role_id]=2

    public function index(Request $request)
    {
        return User::withFilter(new UserFilter, $request)
                    ->orderBy('name')
                    ->get();
    }
}

The above code internally will be called as follow example:

User::where(function ($query) {
    $query->where('name', 'LIKE', 'Wallace%');
    $query->where('role_id', '<>', '2');
})
->orderBy('name')
->get();

What does it do?

This library internally apply filters based on query string parameters with special keyworks names.

See all paramaters follow:

max

The maximum value of a column. The url api/users?max[field]=100 is like a User::where('field', '<=', 100).


min

The minimum value of a column. The url api/users?min[age]=33 is like a User::where('age', '>=', 33).


contains

A search term contained in a column. The url api/users?contains[name]=wallace is like a User::where('name', 'LIKE', '%wallace%').


ends_with

Search a value according to end content of string. Is similar to a LIKE with %$value value.


starts_with

Filter the field when the value starts with a certain value. A url api/users?starts_with[name]=brcontainer Sounds like a User::where('name', 'LIKE', 'brcontainer%').


exact

Search by a exact value of the field· A url api/users?exact[email][email protected] Sounds like a User::where('name', '=', '[email protected]').


has

Filter by relationship. You can use the 0 or 1 value.

Example:

The url api/users?has[posts]=1 is like a User::has('posts')

The url api/users?has[posts]=0 is like a User::doesntHave('posts')


is_null

Apply WHERE IS NULL or WHERE IS NOT NULL to a query.

Example:

The url api/users?is_null[cpf]=1 is like a User::whereNull('cpf')

The url api/users?is_null[age]=0 is like a User::whereNotNull('age')


not_in

Searchs when a column NOT HAS the passed values.

Example:

A url api/users?not_in[role][]=1&not_in[role][]=2 é equivalente à User::whereNotIn('role', [1, 2])

Note: When the not_in[my_field] is a empty array, no action will be taken.


in

Searchs when a column HAS the passed values.

Example:

The url api/users?in[role][]=10&in[role][]=20 sounds like a User::whereIn('role', [10, 20])

NOTE: When the in[my_field] is a empty array, no action will be taken.


date_max

Search by a maximium value of a date field.

A url api/users?date_max[created_at]=2021-01-01 sounds like a User::whereDate('created_at', '<=', '2021-01-01')


date_min

Search by a minimun value of a date field.

Example:

A url api/users?date_min[created_at]=2021-01-01 sounds like a User::whereDate('created_at', '>=', '2021-01-01')


not_equal

Search by not equal value passed. If you use in related field, the whereDoesntHave will be applied applied.

Example:

The url api/users?not_equal[profile_id]=3 sounds like a

User::where('profile_id', '<>', '3');

The url api/users?not_equal[roles.id]=1 sounds like a

User::whereDoesntHave('roles', fn ($query) => $query->where('id', '=', 3));

year_max

The url api/users?year_max[created_at]=2000 sounds like a

User::whereYear('created_at', '<=', 2000);

year_min

The url api/users?year_min[created_at]=1998 sounds like a

User::whereYear('created_at', '>=', 1998);

year_exact

The url api/users?year_exact[created_at]=1998 sounds like a

User::whereYear('created_at', '=', 1998);

Filtering relationship fields

You can apply the search filters in the relatioship methods defined in your model.

For example:

Model:

class User extends Model
{
    use HasFilter;

    public function phones()
    {
        return $this->hasMany(Phone::class, 'user_id');
    }
}

Filters:

class UserFilter extends ModelFilter
{
    public function getFilterables(): array
    {
        return [
            'id'            => ['exact', 'not_equal'],
            'created_at'    => ['year_exact', 'date_max', 'date_min'],
            'phones.number' => ['contains'],
            // or
            'phones'        => new PhoneFilter,
        ];
    }
}

class PhoneFilter extends ModelFilter
{

    public function getFilterables(): array
    {
        return [
            'number' => 'contains'
        ];
    }
}
class UserController extends Controller
{
    public function index()
    {
        // api/users?not_in[role_id][]=1&not_in[role_id][]=3
        
        // select * from users where (role_id NOT IN (1, 3))

        return User::withFilter(new UserFilter)->paginate();
    }

    // Or, apply filter as nested query

    public function index() 
    {

        // api/users?exact[role_id]=1
        
        // select * from users where (role_id = 1)

        return User::where(UserFilter::toClosure())->paginate();
    }

    // Or apply in your query as base condition

    public function index()
    {
        
        // api/users?exact[role_id]=1
        
        // select * from users where role_id = 1

        return User::tap(UserFilter::toClosure())->paginate();
    }
}

In the following example, the user will be filtered for the related phone containing the value 55.

The api/users?exact[phones.number]=55 is like to:

User::where(function ($query) {
    $query->whereHas('phones', function ($query) {
        $query->where('number', '=', '55');
    });
})->paginate();

Axios examples

If you use axios library, you can use the params options to include the above filters.

Example:

const api = axios.create({
    baseURL: 'http://localhost:8000/api'
});

api.get('users', {
    params: { 
        'in[role]' : [1, 2, 3],
        'contains[name]' : 'Maxters',
        'is_null[name]' : 0
    }
})
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].