Answer the question
In order to leave comments, you need to log in
How to modify pagination to display a list according to a certain criterion?
I need to display employees according to a certain criteria, which is specified in the request parameter.
api/employes?page=2&limit=40&tags=3,4
I display users, there are 40 users in the collaget on the 2nd page who have tags 3 and 4.
I figured out how to display the page and the limit, but I can’t display how to display by a specific tag figure it out.
Controller:
public function index(Request $request)
{
$limit = $request->get('limit');
$user = Employe::with('tags')->paginate($limit);
return $user;
}
public function tags()
{
return $this->belongsToMany(Tag::class, 'employe_tag', 'tag_id', 'employe_id');
}
Answer the question
In order to leave comments, you need to log in
I found how to implement
public function index(Request $request)
{
$limit = $request->get('limit');
$tags = $request->get('tags');
$array_tag = explode(",", $tags);
$employes = Employe::query()
->when($array_tag, function($q) use ($array_tag){
$q->whereHas('tags', function($q) use ($array_tag) {
$q->whereIn('tag_id', $array_tag);
});
})->paginate($limit);
return $employes;
}
I would do it through filter:
public function index(Request $request) {
return Employe::with('tags')
->filter($request::all())
->paginateFilter($request->get('limit'));
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question