safoorsafdar / filterable
Laravel Eloquent filterable search functinality
v1.0.0a1
2017-05-05 14:39 UTC
Requires
- php: ~5.6|~7.0
- illuminate/support: ~5.1
Requires (Dev)
- phpunit/phpunit: ~4.0||~5.0
- squizlabs/php_codesniffer: ^2.3
This package is not auto-updated.
Last update: 2024-11-15 20:42:12 UTC
README
Filterable is an package helps to filter the eloquent model based on various condition which already ship with the package.
Install
Via Composer
$ composer require safoorsafdar/filterable
Usage
Model
<?php namespace App\Models\Account; use SafoorSafdar\Filterable\Traits\FilterableTrait; use Illuminate\Database\Eloquent\Model; /** * Class Account * * @package App\Models\Account */ class Account extends Model { use FilterableTrait protected static $filters = [ "name" => \App\Models\Account\Filters\AccountNameFilter::class, ]; }
Note $filterable
array contain the current table attribute name in the database and reference to filter class which will performed the query.
Filter Class
<?php namespace App\Models\Account\Filters; use Illuminate\Database\Eloquent\Builder; use SafoorSafdar\Filterable\Filter\Filter; class AccountNameFilter extends Filter { /** * Apply a given search value to the builder instance. * * @param Builder $builder * @param mixed $value * * @return Builder $builder */ public static function apply( Builder $builder, $value, $condition, $operator ) { $operatorDecorator = self::createOperatorDecorator($condition); if (self::isValidDecorator($operatorDecorator)) { return app($operatorDecorator)->resolve($builder, 'name', $value, $operator); } } }
Controller
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; class AccountController extends Controller { public function index(){ $filters = $request->get('filter', []); return view('account.index') ->withFilterFields(\App\Models\Account\Account::filterableAttributes()) ->withFilterCondition(\Filterable::operators()) ->with("filtered", $filters); } }
View
@include('Filterable::partial.filterable',['filtered'=>$filtered,'filter_fields'=>$filter_fields,'filter_condition'=>$filter_condition])
<script type="text/javascript" src="/js/filterable.js"></script>
Apply submitted Filter to model
$query = Account::with(['user']); $filters = array_filter(array_get($request->all(), 'filter', [])); if ( ! empty($filters)) { $query->applyFilter($filters); } $result = $query->get();
Change log
Please see CHANGELOG for more information on 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 safoor.safdar@gmail.com instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.