skip to Main Content

How do I return the following response format using the code below:

{"data":[],"meta":{"paging":{"links":[],"total":0},"time":0.079}}

The controller code:

public function someMethod()
    {
        $var=SomeModel::with(['status' => function ($query) {
            $query->where('name', 'like', '%Pending Payment%');
        }])->get();

        return [
            'data' => $var,
        ];


    }

Response am getting

{"data":[]}

2

Answers


  1. Chosen as BEST ANSWER

    I was able to solve the problem using Resource Collection

    public function toArray($request)
            {
                return [
                    'data' => $this->collection,
                    'meta' => [
                        'paging' => [
                            'links'=>[],
                             'total'=>0,
                        ],
                    ],
                    'time'=>'',
        
                ];
        
            }
    

  2. $data = Order::query();
    
            // Apply filters and/or sorting to the data query
            // ...
    
            $paginator = $data->paginate(5);
    
            $paginatedData = [
                'data' => $paginator->items(),
                'meta' => [
                    'paging' => [
                        'links' => $paginator->links(),
                        'total' => $paginator->total(),
                    ],
                    'time' => microtime(true) - LARAVEL_START,
                ],
            ];
    
            return response()->json($paginatedData);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search