1

I'm returning some json data as response in a Controller, i want to add some information to

In my DriversController extend's Apicontroller in DriversController i'm returning some data on api call, i want to appent the status code information to below response

if ($request->wantsJson()) {    
    return Response::json([
        'data' => [
            'user_details' => $agent_percentage,
            'dropdown_data' => [
                'employment_types' => $employment_types->all(),
                'roles' => $roles->all(),
                'vehicle_brands' => $vehicle_brands->all(),
                'vehicle_types' => $vehicle_types->all()
            ]
        ]
    ]);
}


   //to the above response
    return Response::json([
        $this->respondSuccess(), // i am append this information
        'data' => [
            'user_details' => $agent_percentage,
            'dropdown_data' => [
                'employment_types' => $employment_types->all(),
                'roles' => $roles->all(),
                'vehicle_brands' => $vehicle_brands->all(),
                'vehicle_types' => $vehicle_types->all()
            ]
        ]
    ]);

In ApiControllre I'm setting all the status code and messages

class ApiController extends Controller 
{

    protected $statusCode = 200;

    //getter status code
    public function getStatusCode() 
    {
        return $this->statusCode;
    }

    //setter status code
    public function setStatusCode($statusCode) 
    {
        $this->statusCode = $statusCode;
        return $this;
    }

    //failure messages
    public function respondFailure($message='Account is not active contact admin', $status='failure')
    {
        return $this->setStatusCode(400)->respondWithMessage($message, $status);
    }

    //success messages
    public function respondSuccess($message='Agent is active', $status='success')
    {
        return $this->setStatusCode(200)->respondWithMessage($message, $status);
    }


    //a layer of abstraction to avoide repetation
    public function respond($data, $headers = []) 
    {
        return Response::json($data, $this->getStatusCode(), $headers);
    }

    //get ststus code and message parse it for errors
    public function respondWithMessage($message, $status) 
    {
        return $this->respond([
            'status_code' => $this->getStatusCode(),
            'status' => $status,
            'message' => $message
        ]);
    }

} 

But the response i'm getting is different as expected

 //expected result
 {
     "status_code": "200",
     "status": "success",
     "message": "User details with dropdown data",
     "data": {
       "user_details": {
          "id": 2017001,
          "name": "User Name",
          "email": "user@email.com",
        },
        "dropdown_data": {

        }
      }
    }

    //getting response
    {
      "0": {
        "headers": {},
        "original": {
          "status_code": 200,
          "status": "success",
          "message": "Agent is active"
        },
        "exception": null
      },
      "data": {
        "user_details": {
          "id": 2017001,
          "name": "User Name",
          "email": "user@email.com",
        },
        "dropdown_data": {

        }
      }
    }

the middleware

<?php

namespace App\Http\Middleware;

use Closure;
use Response;
use App\Http\Controllers\ApiController;

class UserStatus extends ApiController
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($request->user() === null)
        {
            return $this->respondFailure();
        }

        if($request->user()->isActive($request->user()))
        {
            return $next($request);
        }

       return $this->respondFailure();
    }
}
Mr Robot
  • 887
  • 4
  • 18
  • 47

1 Answers1

3

You are only appending the response from the respondSuccess() and not merging the response.

$this->setStatusCode(200)->respondWithMessage($message, $status);

on this response:

return Response::json([
        $this->respondSuccess(), // i am append this information
        'data' => [
            'user_details' => $agent_percentage,
            'dropdown_data' => [
                'employment_types' => $employment_types->all(),
                'roles' => $roles->all(),
                'vehicle_brands' => $vehicle_brands->all(),
                'vehicle_types' => $vehicle_types->all()
            ]
        ]
    ]);

It gives the response as you got not the response you expected.

To get the expected response you need to do something like this:

public function respondWithMessage($message, $status) 
{
    return [
        'status_code' => $this->getStatusCode(),
        'status' => $status,
        'message' => $message
    ];
}

I have used only array and not $this->respond() because you only have this message:

 "status_code": "200",
 "status": "success",
 "message": "User details with dropdown data",

For the type of response, you might need to merge the two arrays into one. Look on array_merge() to get more understanding.

$responseMessage= $this->respondSuccess();
$data = ['data' => [
        'user_details' => $agent_percentage,
        'dropdown_data' => [
            'employment_types' => $employment_types->all(),
            'roles' => $roles->all(),
            'vehicle_brands' => $vehicle_brands->all(),
            'vehicle_types' => $vehicle_types->all()
        ]
    ]
];

$responseArray = array_merge(responseMessage, data);
return Response::json($responseArray);

I have not yet tested the code but this might give you some understanding of how to get the expected array response you want.

If I am wrong anyone could suggest the edit.

PaladiN
  • 4,625
  • 8
  • 41
  • 66
  • your solution worked when returning data in expected format, but i have a problem in my 'ApiController' ihave updated the code with `respond()` function, when returning only `$this->respondSuccess();` i'll get error `Argument 1 passed to Illuminate\Routing\Middleware\ThrottleRequests::addHeaders() must be an instance of Symfony\Component\HttpFoundation\Response, array given, called in C:\wamp64\www\transport_mitra\vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php on line 54 and defined` – Mr Robot Apr 25 '17 at 10:40
  • 1
    So, is that okey with you? If it had helped you that's good :) – PaladiN Apr 25 '17 at 10:44
  • please check my above comment, if i make the `respondWithMessage()` response a an array my `respond()` giving me error – Mr Robot Apr 25 '17 at 10:45
  • Which `Response::json()` are you using?? It should be `Illuminate\Support\Facades\Response` – PaladiN Apr 25 '17 at 11:06
  • i was talking about the `respond()` function in my `ApiController` which is `public function respond($data, $headers = []) { return Response::json($data, $this->getStatusCode(), $headers); }` i have update in my code please do check in `ApiController` – Mr Robot Apr 25 '17 at 11:09
  • i have posted my entire `ApiController` Code, thank you – Mr Robot Apr 25 '17 at 11:13
  • I am unsure about from where the error is comming in your system. Have you tried using only `Response::json($data);` in your `respond()` function. – PaladiN Apr 25 '17 at 11:14
  • i have a `middleware` (updated the code) which is also extending the `ApiController` that is where exactly i'm getting error, rest everything is fine as your solution, thank you – Mr Robot Apr 25 '17 at 11:19
  • thank you so much for your time really appreciate it, i got it fixed thank you – Mr Robot Apr 25 '17 at 11:28