alimousavi / filoquent

Filoquent 是一个强大的 Laravel 扩展包,允许您使用 HTTP 查询参数过滤 Eloquent 模型。

v1.0.2 2024-07-24 21:31 UTC

This package is auto-updated.

Last update: 2024-09-24 21:49:50 UTC


README

Filoquent 是一个强大的 Laravel 扩展包,允许您无缝地使用 HTTP 查询参数过滤 Eloquent 模型。此扩展包简化了在 Laravel 应用程序中构建动态查询过滤器的过程,使得直接通过查询字符串处理复杂的过滤逻辑变得更容易。

功能

  • 动态查询过滤:根据 HTTP 查询参数动态过滤 Eloquent 模型。
  • 易于集成:快速集成到现有的模型和控制台中。
  • 可扩展:创建自定义过滤器以扩展包功能。
  • 支持关系:基于关系和嵌套关系过滤模型。
  • 灵活和可配置:配置默认行为并根据需要覆盖它们。

安装

您可以通过 Composer 安装此包

composer require alimousavi/filoquent

用法

使用特性

要开始使用此包,只需在您的 Eloquent 模型中使用 Filterable 特性即可

use AliMousavi\Filoquent\Filterable;

class Post extends Model
{
    use Filterable;
}

创建过滤器类

Filoquent 提供了一个 artisan 命令,可以轻松生成过滤器类

php artisan make:filter Blog\PostFilter

此命令在 app/Filters 目录中创建一个新的过滤器类。

定义自定义过滤器

您可以通过创建过滤器类来定义自定义过滤器。每个过滤器类都应该扩展 FilterAbstract

namespace App\Filters\Blog;

use AliMousavi\Filoquent\Filters\FilterAbstract;

class PostFilter extends FilterAbstract
{

    /**
     * @var array
     *
     * An array of fields that can be filtered. 
     * They key of array is the field being filtered and the value is the type of the field.
     */
    protected array $filterables = [
        'title' => self::TYPE_STRING,
        'author' => self::TYPE_STRING,
    ];

    /**
     * @var array
     *
     * An array of fields that can be searched. 
     */
    protected array $searchables = [
        'title',
        'content'
    ];

    /**
     * @var array
     *
     * An array of fields that can be used for ordering.
     */
    protected array $orderBy = [
        'published_at' => 'desc',
        'title'
    ];
    
    public function title(string $title){
        $this->builder->where('title', 'like', "%$title%");
    }


    public function author(string $author){
        $this->builder->whereHas('author', function ($query) use ($author) {
            $query->where('name', 'like', "%$author%");
        });
    }
}

应用过滤器

在您的控制器中,现在可以根据查询参数应用过滤器

use Illuminate\Http\Request;
use App\Models\Blog\Post;
use Filters\Blog\PostFilter;
use Http\Resources\Blog\PostResource;

class PostController extends Controller
{
    public function index(Request $request, PostFilter $filter)
    {
        $posts = Post::query()->filter($filter)->paginate();
        
        return PostResource::collection($posts);
    }
}

如果查询参数中的 search 存在,Filoquent 将在提供的数组中的所有字段中搜索。

贡献

欢迎贡献!

许可证

此包是开源软件,使用 MIT 许可证开源:MIT.

鸣谢