otisz/laravel-eloquent-filter

Flexible Eloquent filter from URL queries

v2.3.0 2022-02-16 10:50 UTC

This package is auto-updated.

Last update: 2024-05-16 15:26:23 UTC


README

Latest Version on Packagist Software License Total Downloads

Laravel package for generating flexible Eloquent filters.

Dependencies

Install

You can install the package via Composer

$ composer require otisz/laravel-eloquent-filter

Usage

Use the artisan command to create a new filter class:

$ php artisan make:filter TestFilter

This command generates a new filter class to app/Filters folder:

<?php

namespace App\Filters;

use Illuminate\Http\Request;
use Otisz\EloquentFilter\Filter;

/**
 * @property \Illuminate\Database\Eloquent\Builder $builder
 * @method static \App\Filters\TestFilter boot($class)
 * @mixin \Illuminate\Database\Eloquent\Builder
 */
final class TestFilter extends Filter
{
        /**
         * @param  \Illuminate\Http\Request|null  $request
         *
         * @return self
         */
        public function search(Request $request = null)
        {
            //
    
            return $this;
        }
    
        /**
         * @param  \Illuminate\Http\Request|null  $request
         *
         * @return self
         */
        public function order(Request $request = null)
        {
            //
    
            return $this;
        }
}

How to use in your controller:

There are 3 ways to boot up filter class:

// Eloquent Builder:
TestFilter::boot(Model::query());
TestFilter::boot(Model::where('column', '=', 1));

// Namespace
TestFilter::boot(Model::class);

// Model
TestFilter::boot(new Model);

Filter class contains 2 methods: search() and order().
You can pass \Illuminate\Http\Request or \Illuminate\Foundation\Http\FormRequest to these methods, but not required.

TestFilter::boot(Model::class)->search()->order();

If you call a method that is not defined in the filter class, it will automatically call the Builder class.

For example filter class does not have toSql() method: TestFilter::boot(Model::class)->toSql();

In this case, toSql() method called on Builder class: $this->builder->toSql()

Feel free write your method if needed.

Contributing

Security Vulnerabilities

If you discover any security-related issues, please email leventeotta@gmail.com instead of using the issue tracker. All security vulnerabilities will be promptly addressed.

Licence

The Laravel Eloquent Filter package is open-source software licensed under the MIT license.