使用特征使用Spatie查询构建器过滤数据

时间:2019-05-28 10:02:27

标签: php laravel laravel-5

我将 UserController function index()中的逻辑放在创建的特征中:

public function index()
{
    $this->authorize('view', Auth::user());
    $users = QueryBuilder::for(User::class) 
        ->allowedIncludes('kids','roles','articles','recordings')
        ->allowedFilters('first_name', 'last_name', 'email')
        ->get();
    return UserResource::collection($users);
}

这是我的特质:

<?php
namespace App\Http\Traits;

use App\Models\User;
use Spatie\QueryBuilder\QueryBuilder;

trait Filterable
{
  public function filter()
  {
    $users = QueryBuilder::for(User::class) 
            ->allowedIncludes('kids','roles','articles','recordings')
            ->allowedFilters('first_name', 'last_name', 'email')
            ->get();
            return $users;
  }
}

所以现在我的函数index()看起来像这样:

use Filterable;

    public function index()
    {
        $this->authorize('view', Auth::user());
        $users = $this->filter();
        return UserResource::collection($users);

现在当我在邮递员中这样做时 {{url}}/api/users?filter[first_name]=anna 它可以工作,并且从我的数据库返回anna,但是当我尝试时 {{url}}/api/users?include=roles 它从数据库返回每个用户,但不包括角色。 有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

这是直接从github页面上获取的:https://github.com/spatie/laravel-query-builder#custom-filters

自定义过滤器

use Spatie\QueryBuilder\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;

class FiltersUserPermission implements Filter
{
    public function __invoke(Builder $query, $value, string $property) : Builder
    {
        return $query->whereHas('permissions', function (Builder $query) use ($value) {
            $query->where('name', $value);
        });
    }
}

use Spatie\QueryBuilder\Filter;

// GET /users?filter[permission]=createPosts
$users = QueryBuilder::for(User::class)
    ->allowedFilters(Filter::custom('permission', FiltersUserPermission::class))
    ->get();
// $users will contain all users that have the `createPosts` permission