使用其他索引键自定义JSON响应

时间:2017-05-17 15:16:10

标签: php laravel lumen

我在HTTP Response上使用response()帮助程序,如文档所述。直截了当的用途:

response()->json(
    $this->response,
    $this->status
)->withHeaders([]);

这将输出:

{
    "key" : "desired response"
}

但是,我想在响应中添加一个键:

$return['message'] = 'Request successful';
$return['data'] = response()->json(
    $this->response,
    $this->status
)->withHeaders([]);

但回应的结果是:

{
  "message": "Request successful",
  "data": {
    "headers": {},
    "original": {
      "key" : "desired response"
    },
    "exception": null
  }
}

响应中有额外的键:headersoriginal& exception。我怎样才能摆脱它以达到这种理想的格式:

 {
    "message": "Request successful",
    "data": {
        "key" : "desired response"
    }
 }

2 个答案:

答案 0 :(得分:0)

你可以Laravel Provider

php artisan make:provider ResponseMacroServiceProvider

<?php

namespace App\Providers;

use Response;
use Illuminate\Support\ServiceProvider;

class ResponseMacroServiceProvider extends ServiceProvider
{

    /**
     * Bootrap the application service
     */
    public function boot() {
        Response::macro('success', function ($headers, $originals) {
            return Response::json([
                'message' => "Request successful",
                'data'   => [
                    'headers' => $headers,
                    'original' => $originals,
                ],
                'error' => [
                    'code' => 0 ,
                    'message' => []
                ]
            ]);
        });


        Response::macro('error', function ($message, $status = 400) {
            if(is_array($message))
                $message_repsonse = $message;
            else
                $message_repsonse = [$message];
            return Response::json([
                'message' => "Request failed",
                'data' => [
                    'headers' => null,
                    'original' => null,
                ]
                'error' => [
                    'code' => $status,
                    'message' => $message_repsonse
                ]
            ]);
        });
    }

    /**
     * Register application service
     * @override
     */
    public function register() {

    }

}

修改您的config/app.php

/*
 * Application Service Providers...
*/
App\Providers\ResponseMacroServiceProvider::class,

尝试处理Controller

$headers = 'Your header';
$originals = Your_Model::find(1);

return response()->success($headers, $originals);

return response()->error($validator->errors()->all(), 300);

答案 1 :(得分:0)

您可以使用以下代码实现此目的:

 $return =[] ;
 $return['message'] = 'Request successful'; // your message
 $return['data'] =  $this->response;  // your data
 return response()->json(     // return json
    $return,  // your data here 
    $this->status    // status here
);