mardi 28 mai 2019

Filtering data with spatie query builder

In my function index() of UserController I have this code:

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 $users;
}

so I use spatie QueryBuilder to filter through my User, my rout in postman looks like this:

/api/users?include=recordings,kids,roles,articles&filter[first_name]=anna&filter[last_name]=doe&filter[email]=gmail&sort=first_name

so in every controller that I have index method looks similar. Is there a way to make one filter method in trait or something (to avoid reapiting code) so I could include that trait in my models and my index method would look something like this:

$users = User::filter()
             ->get();

return UserResource::collection($users);



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2YNV5ow
via IFTTT

Aucun commentaire:

Enregistrer un commentaire