Search code examples
laraveleloquenteloquent-relationship

How to do pagination within relation laravel query


   $users = User::whereHas('role', function ($q) {
                $q->where('role_id', 3);
            })
            ->with(['property_managements.new_notifications.type'])
            ->with(['property_managements.new_notifications' => function ($q){
                $q->orderBy('notification_date', 'desc');
            }])
            ->with(['property_managements' => function ($q) {
                $q->whereHas('new_notifications');
            }])
            ->whereHas('property_managements.new_notifications')
            ->get();

I need to paginate the entire data based on "new_notifications" relation data 
That means i want to get users data with paginated based on new_notification relation not based on whole pagination

I have tried pagination along with relation but it did not work. It resulted whole users data.

 
            ->with(['property_managements.new_notifications' => function ($q){
                $q->orderBy('notification_date', 'desc')
                  ->paginate(10);
            }])
         

Solution

  • If you want users data paginated based on New Notifications Date. Then you can do this

    $users = User::whereHas('role', function ($q) {
                    $q->where('role_id', 3);
                })
                ->with(['property_managements.new_notifications.type'])
                ->with(['property_managements.new_notifications' => function ($q){
                    $q->orderBy('notification_date', 'desc');
                }])
                ->with(['property_managements' => function ($q) {
                    $q->whereHas('new_notifications');
                }])
                ->whereHas('property_managements.new_notifications')
                ->orderByDesc(
                  // Considering NewNotification is Model Name and new_notifications is table name
                   NewNotification::select('notification_date') 
                      ->whereColumn('new_notifications.user_id','users.id')
                      ->take(1)
                )
                ->get();
    

    You can also get this using Raw Query which would be like:

    $usersQuery->orderByRaw('(SELECT notification_date FROM new_notifications WHERE new_notifications.id = users.id)')->paginate(10);