ethar's avatar
Level 5

Paginate RelationShip

I get the admin and his activity, I want to paginate activity

            $search = Admins::select('id', 'name', 'photo')
                ->where('id', $id)
                ->with(['adminTracking' => function ($q) use ($request) {
                    $q->select('id', 'events', 'event_id', 'event_type', 'admins_id', 'created_at')
                        ->orderby('id', 'DESC')
                        ->when($request->section, function ($query) use ($request) {
                            $query->where('event_type', $request->section);
                        });
                    $q->paginate(20);
                }]);

but not work, get just 20 items without pagination

admin Model

    public function adminTracking(){
        return $this->hasMany('App\AdminTrackings');
    }
0 likes
3 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Why not split it up?

$admin = Admins::select('id', 'name', 'photo')->find($id);
$tracking = AdminTrackings::select('id', 'events', 'event_id', 'event_type', 'admins_id', 'created_at')
                        ->where('admin_id', $id)
                        ->orderby('id', 'DESC')
                        ->when($request->section, function ($query) use ($request) {
                            $query->where('event_type', $request->section);
                        });
                    $q->paginate(20);
Sinnbeck's avatar

Also your naming is off. The model should be the singular version of the table

Admin = admins table
AdminTracking = admin_trackings table
1 like
davidifranco's avatar

Try this if you don’t want to split it up like @sinnbeck suggests.

$search = Admins::select('id', 'name', 'photo')
   ->where('id', $id)->first()
   ->setRelation('adminTracking' => AdminTracking::where('admin_id', $id)
      ->select('id', 'events', 'event_id', 'event_type', 'admins_id', 'created_at')
       ->orderby('id', 'DESC')
       ->when($request->section, function ($query) use ($request) {
          $query->where('event_type', $request->section);
        })->paginate(20)
   );
           
1 like

Please or to participate in this conversation.