I
I
Ilya Loopashko2021-06-22 10:17:21
Laravel
Ilya Loopashko, 2021-06-22 10:17:21

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


Moddel:
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

2 answer(s)
I
Ilya Loopashko, 2021-06-23
@deadloop

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
Igor Timoshenkov, 2021-06-22
@t1gor

I would do it through filter:

  • Add to project https://github.com/Tucker-Eric/EloquentFilter
  • Run php artisan model:filter App\\Employe
  • In the created filter, add the necessary methods for filtering by relation (it can do this, see the documentation)
  • fix in controller

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 question

Ask a Question

731 491 924 answers to any question