weavers54325
2 years ago
5083
11
Laravel

Paginate while returning array of Api resource objects to the resource collection

Posted 2 years ago by weavers54325

I need to send multiple objects to the api resource colection. So I am returning multiple Objects inside array. Everything works fine but not showing any pagination meta data. like Current_page,next_page url etc.

My resource

<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;

    class ServiceProviderCollection extends  Resource
    {

        public function toArray($request)
        { 

            return
            [  

                'name'=>$this->forename,
                'rating'=>$this->rating,
                'price'=>$this->price,
                'distance'=>round($this->distances,1),

            ];
        }
    }

My Controller

$user_city = $userObj->location->city;
$locationObj = Location::whereNotIn('id', $blockeduser)->where('city',$user_city)->first();
$across_city = $locationObj->users()->simplePaginate(20);

    $near_by =  User::join('locations as l', 'users.location_id', '=', 'l.id')
        ->select('users.*', DB::raw('(6371 * acos(cos(radians(' . $coordinates['latitude'] . ')) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(' . $coordinates['longitude'] . ')) + sin(radians(' . $coordinates['latitude'] . ')) * sin(radians(`lat`)))) as distances'))
        ->having('distances', '<', $max_distance)
        ->orderBy('distances', 'ASC')
        ->where('role_id',2)
        ->whereNotIn('id', $blockeduser)
        ->simplePaginate(20);

    return [
                'across_city' => ServiceProviderCollection::collection($across_city),
                'near_by' => ServiceProviderCollection::collection($near_by)
           ];

I want :

{"data":{
    "across_city": [
        {
            "name": "??",
            "rating": 0,
            "price": 0,
            "distance": 0,

        }
    ],
 "links": {
        "first": "",
        "last": "",
        "prev": null,
        "next": ""
    },
    "meta": {
        "current_page": 1,
        "from": 1,
        "last_page": 3,
        "path": "",
        "per_page": 2,
        "to": 2,
        "total": 6
    },
{
    "near_by": [
        {
            "name": "??",
            "rating": 0,
            "price": 0,
            "distance": 0,

        }
    ],
 "links": {
        "first": "",
        "last": "",
        "prev": null,
        "next": ""
    },
    "meta": {
        "current_page": 1,
        "from": 1,
        "last_page": 3,
        "path": "",
        "per_page": 2,
        "to": 2,
        "total": 6
    }
}

Please sign in or create an account to participate in this conversation.