[扩展包] Laravel-eloquent-filter 减少你对筛选条件搜索 where 的烦恼

在我们日常代码开发中,最常见的功能就是列表筛选了。通过不同的参数,返回符合条件的内容。

在网上也看到不少各种包,写法大同小异,感觉比较繁琐,于是自己写了一个。

下面分享一个扩展包。

安装

composer require james.xue/laravel-eloquent-filter

使用

TestFilter

搜索默认数据库字段
    public function code($code)
    {
        return $this->builder->where('code', $code);
    }

    public function name()
    {
        $this->builder->where('name', 'like', "%测试%");
    }

    public function mobile($mobile)
    {
        $mobile ? $this->builder->where('mobile', $mobile) : $this->builder;
    }

 一对多
    public function title($title)
    {
        return $this->builder->whereHas('goods', function($q) use ($title){
            return $q->where('title', 'like', "%{$title}%");
        });
    }

Controller、通过 url 筛选条件默认方法可以不写,默认搜索条件为 where($column, $keywords)

// http://baby.com/api/city?code=54526481&title=菁华粉底液(片装1.5mll)

public function index(TestFilter $testfilter)
{
    Test::filter($testfilter)->get(); 
    // Or $testfilter 可以省略,默认加载 `模型 + Filter`
    Test::filter()->get(); 

    // 支持固定筛选
    Test::filter($testfilter, 'name')->get();
    // Or
    Test::filter($testfilter, ['name'])->get();

    // 支持固定筛选带参数
    $mobile = "185513215";
    Test::filter($testfilter, ['mobile:'.$mobile])->get();

    // 支持自定义筛选方式,example:<>、like等
    $mobile = "185513215";
    Test::filter($testfilter, ['mobile:'.$mobile."|<>"])->get();
}

扩展包肯定还有不足之处,最后欢迎各位 PR 以带来更好的功能

GitHub:github.com/xiaoxuan6/laravel-eloqu...

本作品采用《CC 协议》,转载必须注明作者和本文链接
不要轻易放弃。学习成长的路上,我们长路漫漫,只因学无止境 Don't give up easily. On the way of learning and growing up, we have a long way to go, just because there is no end to learning.
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!