Skip to content

AidynMakhataev/laravel-filterable

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

LaravelFilterable

Latest Version on Packagist Total Downloads Build Status StyleCI

A laravel package to handle filtering by URL query strings

Installation

Via Composer

$ composer require aidynmakhataev/laravel-filterable

Usage

  1. Create a new filter with the following artisan command:
php artisan make:filter UserFilter

This will create App\Http\Filters\UserFilter.php. You can override the default namespace in config/filterable.php

return [

    /*
    |--------------------------------------------------------------------------
    | Filters Configuration
    |--------------------------------------------------------------------------
    |
    */

    // namespace for the generated filters
    'namespace' =>  'App\Http\Filters'
];

Then, you need to define your filter logic by following this rules:

  • Query string without a corresponding filter method are ignored
  • Empty strings are ignored
  • The value of the each request keys are injected into the corresponding filter method
  • You are able to access the eloquent query builder instance by using $this->builder

Example:

For defining methods for the following url request:

http://yourdomain.com/api/users?gender=male&working=1


You would use the following methods:

namespace App\Http\Filters;

use AidynMakhataev\LaravelFilterable\BaseFilter;

class UserFilter extends BaseFilter
{
    public function gender($value)
    {
        return $this->builder->where('gender', $value);
    }

    public function working($value)
    {
        return $this->builder->where('is_working', $value);
    }
}
  1. Add the trait and bind created in step 1 Filter Class to your model.
use AidynMakhataev\LaravelFilterable\Filterable;

class User extends Authenticatable
{
   use Filterable;

   /**
    * Filters attribute.
    *
    * @var array
    */
   protected $filters = \App\Http\Filters\UserFilter::class;

}
  1. Finally, use it in your Controller:
namespace App\Http\Controllers;

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

class UserController extends Controller
{
    public function index(Request $request)
    {
        $users = User::filter($request->all())->get();

        return response()->json($users);
    }
}

Contributing

Anyone is welcome to contribute. Fork, make your changes, and then submit a pull request.

Security

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

Credits

License

MIT. Please see the license file for more information.