Answer the question
In order to leave comments, you need to log in
What is the best way to implement sorting via get parameters?
I'm building an API in Laravel.
There was a task to give results parts (limit, offset) and with the specified sorting (direction, column).
For offset-limit pagination, I use a package that allows me to call Model::offsetPaginate() instead of the standard Model::paginate() pagination. It works through get parameters, adds information about the current pagination to json meta, everything is as it should be.
It remains only to add sorting with similar requirements.
Of course, models have the orderBy() function and it must be called before calling offsetPaginate(). But there are two unresolved issues:
1. orderBy() has no default values.
2. orderBy() does not check the passed field name (if there is no such field in the table, it will give an error, but I would like to sort in this case by the default field).
2. Information about the current sort is not added to json.
I'm thinking about the following solutions:
1. Add your customOrderBy() function to the model class, in which to add default values if sorting is not specified in get.
2. Add a list of fields allowed for sorting to the model and check the passed field name in customOrderBy().
3. In the resource API, add sorting information to the with function.
What tell me?
Answer the question
In order to leave comments, you need to log in
Laravel Resource also adds meta pagination with the standard paginate(). What exactly is the problem I do not understand. I am doing filtering with a module
class Filter
{
protected $builder;
protected $request;
public function __construct($builder, $request)
{
$this->builder=$builder;
$this->request=$request;
}
public function run()
{
foreach ($this->request->all() as $filter => $value)
{
if (method_exists($this, $filter) and !empty($value))
{
$this->$filter($value);
}
}
return $this->builder;
}
//------------------Фильтры-----------------------------------
private function name($value)
{
$this->builder->where('name', 'like', "%$value%");
}
private function type_id($value)
{
$this->builder->where('type_id', $value);
}
}
return ProductResource::collection($products);
GET /handler?param1=value&sort=model:asc,model2:desc&...
in the controller you parse the parameters and build a request the
specified conditions, if they are in the request, defaults - if not
, validation is required
if there are no default values and what is not there enough - create everything yourself
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question