cerbero90 / query-filters

Laravel package to filter Eloquent model records based on query parameters. Fully inspired by the Laracasts episode https://laracasts.com/series/eloquent-techniques/episodes/4
MIT License
84 stars 15 forks source link

pagination #9

Closed SecretKeeper closed 4 years ago

SecretKeeper commented 4 years ago

hello how can we this package to set per_page filter in pagination ?

class ActorFilters extends QueryFilters
{
    protected function getRules()
    {
        return [
            'per_page' => 'int|digits:4'
        ];
    }
}
public function index(Request $request)
{
    $filters = ActorFilters::hydrate($request->query());

    return Actor::filterBy($filters)->paginate($filters->per_page);
}
cerbero90 commented 4 years ago

Hi @ourfamilygithub, not sure if I understood what you mean but if you need to paginate items depending on the request, the following should work:

return Actor::filterBy($filters)->paginate($request->per_page);
SecretKeeper commented 4 years ago

yeah for now i do that , but i want to get advantage of getRules validation , i don't wanna create a new form request class for each endpoint to validate per_page, with a Trait i can do that for all QueryFilters like this:

<?php

namespace App\Traits;

trait PaginationQueryFilters
{
    protected function getRules()
    {
        return [
            'per_page' => 'int|digits:4'
        ];
    }
} 

and then for each pagination query filters i can do this without creating any extra form request for per_page validation:

<?php

namespace App\QueryFilters;

use App\Traits\PaginationQueryFilters;
use Cerbero\QueryFilters\QueryFilters;

/**
 * Filter records based on query parameters.
 *
 */
class ActorFilters extends QueryFilters
{
    use PaginationQueryFilters;

    /**
     * @param $number
     * @return void
     */

     public function user($user_id) {
         return $this->query->where('user_id', $user_id);
     }
}

now it would be great and clean to use like this: return Actor::filterBy($filters)->paginate($request->per_page);

cerbero90 commented 4 years ago

Right, I see what you mean now. The purpose of getRules() is to apply only filters that pass the validation, filters that don't pass the validation are ignored. In your case per_page is not a filter, rather an arbitrary number to paginate items. I understand that you don't want to repeat the validation of per_page in different requests but that is something that goes outside of the scope of this package.

SecretKeeper commented 4 years ago

oh i see , with my thanks