Eloquent Filter is a package for filter data of models by the query strings. Easy to use and fully dynamic.

Overview

Eloquent Filter

alt text

Latest Stable Version Run tests License GitHub stars StyleCI Build Status Monthly Downloads

Eloquent Filter adds custom filters to your Eloquent Models in Laravel. It's easy to use and fully dynamic.

Bitcoin Donate Button

Table of Content

Requirements

  • PHP 7.2+, 8.0 (new version)
  • Laravel 5.8+,6.x,7.x,8(prefer-stable)

🎤 Introduction

Let's say we want to make an advanced search page with multiple filter option params.

alt text

A simple implementation without Eloquent Filter

The Request URI could look like this:

http://localhost:8000/users/index?age_more_than=25&gender=male&created_at=25-09-2019

And a simple implementation in the Controller would look like this:

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $users = User::where('is_active', true);

        if ($request->has('age_more_than')) {
            $users->where('age', '>', $request->age_more_than);
        }

        if ($request->has('gender')) {
            $users->where('gender', $request->gender);
        }

        if ($request->has('created_at')) {
            $users->where('created_at','>=', $request->created_at);
        }

        return $users->get();
    }
}

This solution is simple and would work fine. But you'd have to add a condition for each filter you need. Especially with more complex filtering your code can become a Monster very fast! 💥

A simple implementation with Eloquent Filter

Eloquent Filter can help you to fix that problem. Just you will set query string to work with that. It will save you time and minimize the complexity of your code.

After installing Eloquent Filter the request URI could look like this:

http://localhost:8000/users/list?age_more_than[operator]=>&age[value]=35&gender=male&created_at[operator]==>&created_at[value]=25-09-2019

And in the controller you'd just need that one line:

/**
 * Class UsersController.
 */

namespace App\Http\Controllers;

use App\User;

class UsersController
{
    public function list()
    {
        return User::filter()->get();
    }
}

With this Eloquent filter implementation you can use all the documented filters!

🔌 Installation

1- Run this Composer command to install the latest version

  $ composer require mehdi-fathi/eloquent-filter
  • Note for Laravel versions older than 5.8 you should install version 2.2.5

      $ composer require mehdi-fathi/eloquent-filter:2.2.5
    

2- Add eloquentFilter\ServiceProvider::class to provider app.php

'providers' => [
  /*
   * Package Service Providers...
   */
    eloquentFilter\ServiceProvider::class
],

3- Add Facade 'EloquentFilter' => eloquentFilter\Facade\EloquentFilter::class to aliases app.php

'alias' => [
  /*
   * Facade alias...
   */
    'EloquentFilter' => eloquentFilter\Facade\EloquentFilter::class,
],

That's it enjoy! 💥

📖 Basic Usage

Config Model and set whitelist

Add Filterable trait to your models and set fields that you will want filter in whitelist. You can override this method in your models.

use eloquentFilter\QueryFilter\ModelFilters\Filterable;

class User extends Model
{
    use Filterable;
    
    private static $whiteListFilter =[
        'id',
        'username',
        'email',
        'created_at',
        'updated_at',
    ];
}

You can set * char for filter in all fields as like below example:

private static $whiteListFilter = ['*'];

You can add or set $whiteListFilter on the fly in your method.For example:

Set array to WhiteListFilter

  • Note that this method override $whiteListFilter
User::setWhiteListFilter(['name']); 

Add new field to WhiteListFilter

User::addWhiteListFilter('name'); 

Use in Controller

Change your code on controller of laravel as like below example:

namespace App\Http\Controllers;

/**
 * Class UsersController.
 */
class UsersController
{

    public function list()
    {
          if (!empty(request()->get('username'))) {
          
              $users = User::ignoreRequest('perpage')->filter()->with('posts')
                        ->orderByDesc('id')->paginate(request()->get('perpage'),['*'],'page');

          } else {
              $users = User::filter(
                ['username' => ['mehdi','ali']]           
                )->with('posts')->orderByDesc('id')->paginate(10,['*'],'page');
          }
    }
}

-Note that the Eloquent Filter by default using the query string to make queries in the laravel. Also, you can set the array to filter method Model for making your own custom condition without query string.

-Note that you must unset your own param as perpage. Just you can set page param for paginate this param ignore from filter.

  • You can ignore some request params by use of code it.
User::ignoreRequest(['perpage'])
            ->filter()
            ->paginate(request()->get('perpage'), ['*'], 'page');

Call ignoreRequest will ignore some requests that you don't want to use in conditions eloquent filter. For example perpage param will never be in the conditions eloquent filter. it's related to the paginate method. page param ignore by default in the Eloquent Filter Laravel.

  • You can filter some request params for using in eloquent filter.
User::AcceptRequest(['username','id'])
            ->filter()
            ->paginate(request()->get('perpage'), ['*'], 'page');

Call AcceptRequest will accept requests that you want to use in conditions eloquent filter. For example username and id param will be in the conditions eloquent filter. Just notice you must set $whiteListFilter in Model. This method is useful for query string manipulation by user.

  • Another example use of a filter eloquent filter.
User::filter()->paginate();
  • EloquentFilter::filterRequests() get all params that used by the Eloquent Filter. You can set key to get specific index. For example EloquentFilter::filterRequests('username') it's getting username index.

  • EloquentFilter::getAcceptedRequest() get all params that set by the AcceptRequest method.

  • EloquentFilter::getIgnoredRequest() get all ignored params that set by the getIgnoreRequest method.

Simple Examples

You just pass data blade form to query string or generate query string in controller method. For example:

Simple Where

/users/[email protected]

SELECT ... WHERE ... email = '[email protected]'
/users/list?first_name=mehdi&last_name=fathi

SELECT ... WHERE ... first_name = 'mehdi' AND last_name = 'fathi'

Where In

This example make method whereIn.

/users/list?username[]=ali&username[]=ali22&family=ahmadi

SELECT ... WHERE ... username in ('ali','ali22') AND family = 'ahmadi'

OrWhere (New feature 🔥 )

This example make method orWhere.

/users/list?name=mehdi&username=fathi&or[username]=ali

SELECT ... WHERE ... name = 'mehdi' AND username = 'fathi' or username = 'ali'

Where like

If you are going to make query by like conditions. You can do it that by this example.

/users/list?first_name[like]=%John%

SELECT ... WHERE ... first_name LIKE '%John%'

Where by operator

You can set any operator mysql in query string.

/users/list?count_posts[operator]=>&count_posts[value]=35

SELECT ... WHERE ... count_posts > 35
/users/list?username[operator]=!=&username[value]=ali

SELECT ... WHERE ... username != 'ali'
/users/list?count_posts[operator]=<&count_posts[value]=25

SELECT ... WHERE ... count_posts < 25

Where the nested relation Model (New feature 🔥 )

You can set all nested relation in the query string just by the array query string. For example, the user model has a relation with posts. and posts table has a relation with orders. You can make query conditions by set 'posts[count_post]' and 'posts[orders][name]' in the query string. Just be careful you must set 'posts.count_post' and 'posts.orders.name' in the User model.

use eloquentFilter\QueryFilter\ModelFilters\Filterable;

class User extends Model
{
    use Filterable;
   
    private static $whiteListFilter =[
        'username',
        'posts.count_post',
        'posts.category',
        'posts.orders.name',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\belongsTo
     */
    public function posts()
    {
        return $this->belongsTo('Models\Post');
    }

}
/users/list?posts[count_post]=876&username=mehdi

select * from "users" where exists 
         (select * from "posts" where "posts"."user_id" = "users"."id" 
         and "posts"."count_post" = 876)
         and "username" = "mehdi"
  • The above example as the same code that you use without the eloquent filter. Check it under code.
$user = new User();
$builder = $user->with('posts');
        $builder->whereHas('posts', function ($q) {
            $q->where('count_post', 876);
        })->where('username','mehdi');

Where array the nested relation Model

You can pass array to make whereIn condition.

/users/list?posts[category][]=php&posts[category][]=laravel&posts[category][]=jquery&username=mehdi

select * from "users" where exists 
         (select * from "posts" where 
         "posts"."category" in ('php','laravel','jquery') )
         and "username" = "mehdi"

Special Params

You can set special params limit and orderBy in query string for make query by that.

/users/list?f_params[limit]=1

SELECT ... WHERE ... order by `id` desc limit 1 offset 0
/users/list?f_params[orderBy][field]=id&f_params[orderBy][type]=ASC

SELECT ... WHERE ... order by `id` asc
/users/list?f_params[orderBy][field]=id,count_posts&f_params[orderBy][type]=ASC

SELECT ... WHERE ...  order by `id` asc, `count_posts` asc

Where between

If you are going to make query whereBetween.You must fill keys start and end in query string. you can set it on query string as you know. this params is good fit for filter by date.

/users/list?created_at[start]=2016/05/01&created_at[end]=2017/10/01

SELECT ... WHERE ... created_at BETWEEN '2016/05/01' AND '2017/10/01'

Advanced Where

/users/list?count_posts[operator]=>&count_posts[value]=10&username[]=ali&username[]=mehdi&family=ahmadi&created_at[start]=2016/05/01&created_at[end]=2020/10/01
&f_params[orderBy][field]=id&f_params[orderBy][type]=ASC

select * from `users` where `count_posts` > 10 and `username` in ('ali', 'mehdi') and 
`family` = ahmadi and `created_at` between '2016/05/01' and '2020/10/01' order by 'id' asc limit 10 offset 0

Just fields of query string be same rows table database in $whiteListFilter in your model or declare method in your model as override method. Override method can be considered custom query filter.

Custom Query Filter

The Eloquent Filter doesn't support all of the conditions by default. For this situation you can make a override method. If you are going to make yourself query filter you can do it easily. You just make a trait and use it on model:

use Illuminate\Database\Eloquent\Builder;

/**
 * Trait usersFilter.
 */
trait usersFilter
{
    /**
     * @param \Illuminate\Database\Eloquent\Builder $builder
     * @param                                       $value
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function username_like(Builder $builder, $value)
    {
        return $builder->where('username', 'like', '%'.$value.'%');
    }
}

-Note that fields of query string be same methods of trait. Use trait in your model:

/users/list?username_like=a

select * from `users` where `username` like %a% order by `id` desc limit 10 offset 0
class User extends Model
{
    use usersFilter,Filterable;

    protected $table = 'users';
    protected $guarded = [];
    private static $whiteListFilter =[
        'id',
        'username',
        'email',
        'created_at',
        'updated_at',
    ];
    
}

-Note that fields of query string be same methods of trait. Use trait in your model:

/users/list?username_like=a
select * from `users` where `username` like %a% order by `id` desc limit 10 offset 0
class User extends Model
{
    use usersFilter,Filterable;

    protected $table = 'users';
    protected $guarded = [];
    private static $whiteListFilter =[
        'id',
        'username',
        'email',
        'created_at',
        'updated_at',
    ];
    
}

Custom Detection Condition

Sometimes you want to make your own custom condition for make new query that eloquent filter doesn't support it by default. Good news you can make custom condition in the eloquent filter from now on. In fact you can make condition for the generate new query after check by that (New feature 🔥 ). For example :

We must make two class first class to detect conditions another class to generate query.

  • Step 1: Create a class to detect the condition
use eloquentFilter\QueryFilter\Detection\DetectorContract;

/**
 * Class WhereRelationLikeCondition.
 */
class WhereRelationLikeCondition implements DetectorContract
{
    /**
     * @param $field
     * @param $params
     * @param $is_override_method
     *
     * @return string|null
     */
    public static function detect($field, $params, $is_override_method = false): ?string
    {
        if (!empty($params['value']) && !empty($params['limit']) && !empty($params['email'])) {
            $method = WhereRelationLikeConditionQuery::class;
        }

        return $method ?? null;
    }
}
  • Step 2: After that create a class to generate query. In this example we make WhereRelationLikeConditionQuery class:
use eloquentFilter\QueryFilter\Queries\BaseClause;
use Illuminate\Database\Eloquent\Builder;

/**
 * Class WhereRelationLikeConditionQuery.
 */
class WhereRelationLikeConditionQuery extends BaseClause
{
    /**
     * @param $query
     *
     * @return Builder
     */
    public function apply($query): Builder
    {
        return $query
            ->whereHas('posts', function ($q) {
                $q->where('comment', 'like', "%" . $this->values['like_relation_value'] . "%");
            })
            ->where("$this->filter", '<>', $this->values['value'])
            ->where('email', 'like', "%" . $this->values['email'] . "%")
            ->limit($this->values['limit']);
    }
}
  • Step 3: You just make the method EloquentFilterCustomDetection for return array detections of the condition in the model.
use eloquentFilter\QueryFilter\ModelFilters\Filterable;

class User extends Model
{
    use Filterable;
   
    private static $whiteListFilter =[
        'username',
        'posts.count_post',
        'posts.category',
        'posts.orders.name',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\belongsTo
     */
    public function posts()
    {
        return $this->belongsTo('Models\Post');
    }

    public function EloquentFilterCustomDetection(): array
    {
        return [
            WhereRelationLikeCondition::class
        ];
    }

}
  • Every query params are going to detect in WhereRelationLikeCondition for the first time after that check by default detection eloquent filter.

Make method EloquentFilterCustomDetection in the above example and return array conditions class.

/users/list?username[value]=mehdi&username[limit]=10&username[email]=mehdifathi&username[like_relation_value]=mehdi&count_posts=10

select * from "users"
 where exists (select * from "posts" where 
"users"."post_id" = "posts"."id" 
and "comment" like ?) and "username" <> ? and "email" like ? and "count_posts" = ? limit 10

You just run code User::filter(); for see result.

-Note Also you can set custom detection on the fly by use of method SetCustomDetection. For example :

$users = User::SetCustomDetection([WhereRelationLikeCondition::class])->filter();

-Note You can disable EloquentFilterCustomDetection on the fly by this code :

 User::SetLoadDefaultDetection(false)->filter();

-Note You can set many detection conditions for example:

class User extends Model
{
    use Filterable;
    public function EloquentFilterCustomDetection(): array
    {
        return [
            WhereRelationLikeCondition::class,
            WhereRelationLikeVersion2Condition::class,
            WhereRelationLikeVersion3Condition::class,
        ];
    }
}
  • EloquentFilter::getInjectedDetections() get all your custom injected detection.

-Note Every custom detection will run before detection by default eloquent filter.

Configuring

You can generate a config file to configure Eloquent Filter. Has amazing features for your project.

Publish Config

php artisan vendor:publish --provider="eloquentFilter\QueryFilter\ServiceProvider"

Config

  • You can disable/enable Eloquent Filter in config file (eloquentFilter.php).

      'enabled' => env('EloquentFilter_ENABLED', true),
    
  • Eloquent Filter recognizes every param of query string to pass it. Maybe you have a query string that you don't want recognize by Eloquent Filter. You can using of ignoreRequest for his purpose. But we have clean solution to this problem. You can set param request_filter_key in the config file. Therefore every query string will recognize by request_filter_key param.

      'request_filter_key' => '', // filter
    

For example, if you set 'request_filter_key' => 'filter', that Eloquent Filter recognizes filter query string.

/users/list?filter[email][email protected]

  • You can disable/enable custom detection of Eloquent Filter in the config file (eloquentFilter.php).

      'enabled_custom_detection' => env('EloquentFilter_Custom_Detection_ENABLED', true),
    
  • You should set index array in ignore_request to ignore by in all filters.

      'ignore_request' => [] //[ 'show_query','new_trend' ],
    

Magic Methods

Magic methods are a collection of methods that you can use of them as wrapper in the Eloquent Filter. For example, serialize data before filter or change data in response and others. Now Eloquent Filter have serializeRequestFilter,ResponseFilter.

Request Filter

Eloquent Filter has a magic method for just change requests injected before handling by eloquent filter. This method is SerializeRequestFilter. You just implement SerializeRequestFilter method in your Model. For example

class User extends Model
{
    use Filterable;
    public function serializeRequestFilter($request)
    {
       $request['username'] = trim($request['username']);
       return $request;
    }
}

As above code you can modify every query params of the Model in the method serializeRequestFilter before run by Eloquent Filter. This is a good method when you want set user_id or convert date or remove space and others.

Response Filter

Response Filter is a magic method for just change response after handling by Eloquent Filter. This method is ResponseFilter. You should implement ResponseFilter method in your Model. For example

class User extends Model
{
    use Filterable;
    public function ResponseFilter($response)
    {
        $data['data'] = $response;
        return $data;
    }
}
  • If you have any idea about the Eloquent Filter i will glad to hear that. You can make an issue or contact me by email. My email is [email protected].
Comments
  • handle Exception

    handle Exception

    HI Author,

    i m using this, it so far is very good and helpful but now i m getting on issue with it.

    when i set in model $whiteListFilter = ['id']

    it should mean ?id will handle by this library rest user can handle own but now it is looking for ?anykey it should happen if user $whiteListFilter = ['*'] add like this

    blow is the code which you need to look

    https://github.com/mehdi-fathi/eloquent-filter/blob/c576a1a44c1b51ca371db177e83e9694a75bb72b/src/QueryFilter/Detection/DetectorConditions.php#L77

    Thanks you

    opened by Kamleshpaul 11
  • WhereIn request for relationships

    WhereIn request for relationships

    I have relation like ' order_details[markets][market_id] ' , and making form get request with select2 multiple parameter.

    How to pass the array to request, now I'm getting error like

    Call to undefined method App\Models\Markets:market_id()

    when I add [] in the last of name attribute like order_details[markets][market_id][], same with order_details[][markets][market_id]

    P.S. Thanks for the extension, it's pretty good and understandable than spatie-query-builder. Good job man

    opened by uzkurama 10
  • Target class [eloquentFilter] does not exist.

    Target class [eloquentFilter] does not exist.

    Hello, unfortunately I can't get this extension to work. I tried a few months ago, but failed because of the same problem as now.

    Error message: Target class [eloquentFilter] does not exist.

    I made all adjustments according to the instructions. Also in the app.php file I inserted both lines according to the instructions. Can someone please help me?

    Model:

    <?php
    
    namespace App;
    
    use eloquentFilter\QueryFilter\ModelFilters\Filterable;
    use Illuminate\Database\Eloquent\Model;
    #use Illuminate\Database\Eloquent\Builder;
    
    class Files extends Model
    {
        use Filterable;
    
    	public $timestamps = false;
    	protected $fillable = ["user_id", "relative_path", "filename", "fileextension", "insert_time", "file_last_changed", "last_scan_touch", "last_analysed_metadata", "last_convert_run", "last_recognition_run", "probably_deleted"];
    
    
        /**
         * @var array
         */
        private static $whiteListFilter = ['*'];
    

    Controller:

    <?php
    
    namespace App\Http\Controllers;
    
    use App\Files;
    use App\FileMetatags;
    use App\FilesLocation;
    use DateTime;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Validator;
    use Illuminate\Support\Facades\DB;
    use Illuminate\Support\Facades\Auth;
    
    class FileController extends Controller
    {
    
        /**
         * Display a listing of the resource.
         *
         * @return \Illuminate\Http\Response
         */
    
        public function indexJSON() {
    
            $filesFiltered = Files::filter();
    
            dd($filesFiltered);
    
    opened by maisen20 9
  • Possible to make queries for relationships?

    Possible to make queries for relationships?

    Hello, great library. I wondered if it's possible to support relationship models? Lets say I have Orders model, and there Order Shipment model. Relationship looks like $this->hasOne('OrderShipment', [primary_key]).

    Now, when we query the information, I need to able search in these related models. for example, I'd like to have something like &order_shipment.status=New

    Final SQL should be something like SELECT .. WHERE ... AND order_shipment.status = 'New'.

    opened by orenlande 9
  • ignoreRequest

    ignoreRequest

    First, sorry by me english!!

    Describe the bug You must set perpage in whiteListFilter in model.php or create a override method with name perpage or call ignoreRequest function for ignore perpage

    To Reproduce My code:

    public function index()
    {
    Model::ignoreRequest(['links','meta','page','perpage'])->orderBy('id', 'Desc')->MyScope()->filter()->paginate()->appends(request()->query());
    }
    
    opened by laymont 8
  • eloquent-filter doesn't work Laravel 7.4

    eloquent-filter doesn't work Laravel 7.4

    I have a new project that is based on Laravel 7.4 and when I run the command to add eloquent-filter dependency, it crashes: To Reproduce Running the comand inside a Laravel 7.4 project: composer require mehdi-fathi/eloquent-filter

    Errors: 02:04 $ composer require mehdi-fathi/eloquent-filter Using version ^1.6 for mehdi-fathi/eloquent-filter ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages.

    Problem 1 - Conclusion: remove laravel/framework v7.4.0 - Conclusion: don't install laravel/framework v7.4.0 - mehdi-fathi/eloquent-filter 1.6.0 requires illuminate/pagination 5.5.|5.6.|5.7.|5.8.|^6.0|^6.1 -> satisfiable by illuminate/pagination[5.5.x-dev, 5.6.x-dev, 5.7.17, 5.7.18, 5.7.19, 5.7.x-dev, 5.8.x-dev, 6.x-dev, v5.5.0, v5.5.16, v5.5.17, v5.5.2, v5.5.28, v5.5.33, v5.5.34, v5.5.35, v5.5.36, v5.5.37, v5.5.39, v5.5.40, v5.5.41, v5.5.43, v5.5.44.........

    • don't install illuminate/pagination v6.7.0|don't install laravel/framework v7.4.0
      • don't install illuminate/pagination v6.8.0|don't install laravel/framework v7.4.0
      • Installation request for laravel/framework (locked at v7.4.0, required as ^7.0) -> satisfiable by laravel/framework[v7.4.0].
      • Installation request for mehdi-fathi/eloquent-filter ^1.6 -> satisfiable by mehdi-fathi/eloquent-filter[1.6.0, 1.6.0.x-dev].

    If you think I'm doing something wrong, please tell me. Let's talk about it

    opened by paduanton 8
  • In Your Like condition, This Dependency  Block the

    In Your Like condition, This Dependency Block the " Delhi " word in Query show empty result but exist data

    test.com/api/v1/testas?a_state[like]=%Delhi% through postman show empty { "data": [] } but in other state show data . and all city existed only problem with delhi . using your default condition of where like

    opened by Deepakcyber 7
  • Use custom exceptions for better error handling

    Use custom exceptions for better error handling

    Is your feature request related to a problem? Please describe. The package often throws exception which is very good for error handling and debugging. But catching or handling those exceptions are kind of problematic. Since the package only throws \Exception, it's hard to catch them by their specific name as all exceptions extend this base Exception class. So it would be good if those exceptions were custom made.

    Describe the solution you'd like Create and throw custom exception classes that extend the base \Exception class. For example, EloquentFilterException etc. So, one can simply do this:

    try {
    //...
    } catch (\eloquentFilter\Exceptions\EloquentFilterException $e) {
    } catch(\AnyOtherException $e) {
    }
    

    Thanks.

    Describe alternatives you've considered

    Additional context

    opened by MirazMac 4
  • ignoreRequest sets

    ignoreRequest sets "deleted_at is null"

    Describe the bug I try to filter on a model including trashed entries. This works as designed, however, adding ignoreRequest() adds where deleted_at is null to the query, which is definitely not intended. I don't see any reason why especially ignoreRequest should add that.

    To Reproduce Steps to reproduce the behavior:

    1. Add a filter to a query including trashed entries (::withTrashed()). The result includes trashed entries (if exist).
    2. Add ignoreRequest() to the builder. The result does not include trashed entries anymore.

    Here is some boilerblade code:

    dump($request->input());
    dump(Vehicle::withTrashed()->filter()->toSql());
    dump(Vehicle::withTrashed()->ignoreRequest(["id"])->toSql()); //ignoring id for demonstration
    dd(Vehicle::withTrashed()->ignoreRequest(["id"])->filter()->toSql());
    

    The result:

    array:1 [
      "id" => "1"
    ]
    
    "select * from `vehicles` where `id` = ?"
    
    "select * from `vehicles` where `vehicles`.`deleted_at` is null"
    
    "select * from `vehicles` where `vehicles`.`deleted_at` is null"
    

    Expected behavior I expect that calling ignoreRequest() does not modify the query in that way (i.e. only fields listed as argument should be ignored).

    Workaround Just remove the desired field (which should be ignored) from the request and add it again afterwards.

    $id = $request->input("id");
    $request->request->remove("id");
    $vehicles = Vehicle::withTrashed()->filter()->get(); //Cannot call ignoreRequest(['rent']) as else filtered by deleted_at
    
    //Add it back to make default laravel functions work properly
    $request->request->add([
        'id' => $id
    ]);
    dd($vehicles);
    

    Versions:

    • Laravel: v8.27.0
    • Your Eloquent Filter: v2.4.4
    • PHP: v7.4.11

    Additional context I tried this in a fresh laravel project as well, just to confirm my observation.

    opened by ClProsser 4
  • Add date function to the  where query for created_at/updated_at and other TIMESTAMP columns

    Add date function to the where query for created_at/updated_at and other TIMESTAMP columns

    Is your feature request related to a problem? Please describe. One of the problems I'm facing right now while using this is, whenever I try to use the conditions on TIMESTAMP fields:

    For example: ?created_at[operator]==&created_at[value]=2022-07-14

    This will generate this query:

    select * from `contents` where  `created_at` = '2022-07-14'
    

    And since Laravel stores the created_at field as a TIMESTAMP column, the query won't return any result.

    On the other hand, Eloquent's whereDate() scope works, as it generates this query:

    select * from `contents` where date(`created_at`) = '2022-07-14'
    

    Describe the solution you'd like

    My suggestion is to use the date() function to the where query just like Eloquent's whereDate() does, if the column's name are created_at / updated_at. Or perhaps this can be set in a model property for any other fields like:

    public static array $filterUseDate = ['created_at'];
    

    Great package btw. Thanks.

    opened by MirazMac 3
  • Support for DB Query Builder

    Support for DB Query Builder

    Is your feature request related to a problem? Please describe. Not related to a problem

    Describe the solution you'd like I would like to be able to use filters with the Query builder, not just Eloquent

    Describe alternatives you've considered I have not found any alternatives

    opened by vicenterusso 3
  • LIKE's search sometimes changes the value's character format

    LIKE's search sometimes changes the value's character format

    When I make a call to my API with paramters to use LIKE filter it happens that the format of the passed value is cahnged to not UTF8. This problem causes the error "Malformed UTF-8 characters, possibly incorrectly encoded"

    Example of a call to my API's backend: api/clienti?cliente[LIKE]=%CALOI%

    opened by brusacla 1
  • Support elastic search & Full-Text Search MySQL

    Support elastic search & Full-Text Search MySQL

    -Support elastic search can be a big feature that to be practical and wonderful to all projects. -Support Full-Text Search MySQL can be a good feature

    opened by mehdi-fathi 0
Releases(3.0.4)
Owner
Mehdi Fathi
I'm working with PHP, Laravel, Js, and other things.
Mehdi Fathi
MOP is a php query handling and manipulation library providing easy and reliable way to manipulate query and get result in a fastest way. ( WEBSITE VERSION )

Mysql Optimizer mysql optimizer also known as MOP is a php query handling and manipulation library providing easy and reliable way to manipulate query

null 3 Feb 14, 2022
A simple program to query mysql data and display the queried data in JSON format

A simple program to query mysql data and display the queried data in JSON format. The data displayed in JSON format will change and update as the data in your mysql database changes.

null 2 Mar 7, 2022
A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Laravel MongoDB This package adds functionalities to the Eloquent model and Query builder for MongoDB, using the original Laravel API. This library ex

Jens Segers 6.3k Jan 5, 2023
⚡️ Models like Eloquent for Elasticsearch.

Elasticsearch Eloquent 2.x This package allows you to interact with Elasticsearch as you interact with Eloquent models in Laravel. Requirements PHP >=

Sergey Sorokin 111 Dec 19, 2022
The query sorting bundle allows you to sort data from QueryBuilder and the Database

The query sorting bundle allows you to sort data from QueryBuilder and the Database. you can sort multiple columns at the same time and also you can sort relation fields with two-level deep and without any join in your query builder.

Bugloos 12 Oct 6, 2022
Simple MySQL library for PHP 5.4+ includes Query Builder, PDO Native functions, Helper functions for quick use.

Simple MySQL library for PHP 5.4+ includes Query Builder, PDO Native functions, Helper functions for quick use.

Kodols 9 Dec 22, 2022
A Redis based, fully automated and scalable database cache layer for Laravel

Lada Cache A Redis based, fully automated and scalable database cache layer for Laravel Contributors wanted! Have a look at the open issues and send m

Matt 501 Dec 30, 2022
A lightweight nearly-zero-configuration object-relational mapper and fluent query builder for PHP5.

Idiorm http://j4mie.github.com/idiormandparis/ Feature/API complete Idiorm is now considered to be feature complete as of version 1.5.0. Whilst it wil

Jamie Matthews 2k Dec 27, 2022
Independent query builders for MySQL, PostgreSQL, SQLite, and Microsoft SQL Server.

Aura.SqlQuery Provides query builders for MySQL, Postgres, SQLite, and Microsoft SQL Server. These builders are independent of any particular database

Aura for PHP 424 Dec 12, 2022
Very easy to use PDO MYSQL API. Just Include in PHP file and get it working.

CRUD-MYSQL-API Very easy to use PDO MYSQL API. Just Include in PHP file and get it working. INSTALATION Step 1: git clone https://github.com/arhex-lab

Abdul Raheem 4 Jun 14, 2022
Easy data transfer from one database to another

Migrate DB Easy data transfer from one database to another Installation To get the latest version of Migrate DB, simply require the project using Comp

The Dragon Code 130 Dec 7, 2022
A SQL query builder with zero dependencies

Latitude Query Builder A SQL query builder with zero dependencies. Attempts to be PSR-1, PSR-2, and PSR-4 compliant. Install composer require latitude

Woody Gilk 618 Dec 30, 2022
SQL to Laravel Query Builder

Marwan - SQL To Laravel Builder SQL to Laravel Query Builder, A Converter written in PHP Features Converts SQL Queries to Laravel Query Builder. Assis

Rexhep Shijaku 162 Dec 19, 2022
Database Abstraction Layer, Schema Introspection, Schema Generation, Query Builders

Cycle DBAL Secure, multiple SQL dialects (MySQL, PostgreSQL, SQLite, SQLServer), schema introspection, schema declaration, smart identifier wrappers,

Cycle ORM 30 Oct 18, 2022
Get MYSQL statement from query builder in laravel helper

Get MYSQL statement laravel This package allows to get mysql statement that query builder in laravel made it for debugging purposes. Basic usage Dump

Ahmed Helal 9 Jul 15, 2022
A PHP client driver for the RethinkDB query language (ReQL).

PHP-RQL A PHP client driver for the RethinkDB query language (ReQL).

Daniel Mewes 341 Dec 30, 2022
ATK Data - Data Access Framework for high-latency databases (Cloud SQL/NoSQL).

ATK Data - Data Model Abstraction for Agile Toolkit Agile Toolkit is a Low Code framework written in PHP. Agile UI implement server side rendering eng

Agile Toolkit 257 Dec 29, 2022
Easy-to-use PDO wrapper for PHP projects.

EasyDB - Simple Database Abstraction Layer PDO lacks brevity and simplicity; EasyDB makes separating data from instructions easy (and aesthetically pl

Paragon Initiative Enterprises 705 Dec 9, 2022
An easy-to-use Artisan command to create a new database schema.

Laravel Create DB This package adds an easy-to-use Artisan command to your application that allows you to create a new database schema. The package is

Aron Rotteveel 11 Dec 29, 2022