dansmith/eloquent-filterable

Filter scope for Eloquent models

dev-master 2017-10-13 13:57 UTC

This package is not auto-updated.

Last update: 2024-11-09 19:23:49 UTC


README

#Eloquent Filterable

A simple package for filtering records, using varying user input.

##Installation

Add the package to your composer.json file and run composer update:

{
	"require" : {
	  "dansmith/eloquent-filterable": "dev-master"
	}
}

##Basic Use

Import the trait and use in your Eloquent model

use DanSmith\Filterable\Filterable;

class Page extends Model {

    use Filterable;

}

Specify the attributes you want to filter by (any values not specified here will be ignored):

protected $filterable = ['category_id', 'created_by'];

Alternatively, if you want to provide more complex filters, you can override the getFilterable method. This makes it possible to provide either a closure or a custom class.

public function getFilterable()
{
    return [
    	'category_id',
    	'created_by',
    	'starts_with' => function($query, $value) { return $query->where('title', 'LIKE', $value.'%'); }
    ];
}

Run an Eloquent query with using your parameters

$parameters = ['category_id' => 1, 'created_by' => 2];
$pages = Page::filter($parameters)->orderBy('title', 'asc')->paginate();

Taking parameters directly from the URL

$pages = Page::filter($request->all())->orderBy('title', 'asc')->paginate();