dansmith/eloquent-filterable

过滤 Eloquent 模型的作用域

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

This package is not auto-updated.

Last update: 2024-09-14 18:26:16 UTC


README

#Eloquent Filterable

一个简单的用于过滤记录的包,使用可变用户输入。

##安装

将包添加到您的 composer.json 文件中,并运行 composer update

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

##基本使用

导入特质并在您的 Eloquent 模型中使用

use DanSmith\Filterable\Filterable;

class Page extends Model {

    use Filterable;

}

指定您想要过滤的属性(未在此处指定的任何值都将被忽略)

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

或者,如果您想提供更复杂的过滤器,您可以覆盖 getFilterable 方法。这使得您可以提供一个闭包或自定义类。

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

使用您的参数运行 Eloquent 查询

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

直接从 URL 中获取参数

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