【问题标题】:how to return a response object json in laravel如何在laravel中返回响应对象json
【发布时间】:2016-12-07 16:29:31
【问题描述】:

我已经收到回复,但我不需要这样的回复

{
  "status": "200",
  "id": 1,
  "email": "a@a.a",
  "mobile": "",
  "source": "",
  "source_id": "",
  "message": "Bad Request : Already Logged In"
}

我需要在另一个对象中返回此数据,例如:

{
 {
  "status": "200",
 }
 { 
  "id": 1,
  "email": "a@a.a",
  "mobile": "",
  "source": "",
  "source_id": "",
  "message": "Bad Request : Already Logged In"
 }
}

【问题讨论】:

  • 有什么问题?到目前为止你尝试过什么?
  • 第二个是无效的json格式。而且我不这么认为,第一个解析有任何问题。但是你使用的格式像 { "status": "200", "details": { "id": 1, "email": "a@aa", "mobile": "", "source": "", "source_id": "", "message": "错误请求:已经登录" } }
  • 我已经得到了这个解决方案,但与 android 开发人员有一个问题,他不需要像“详细信息”、“数据”等。他需要一个包含直接数据的响应,例如 { "id" : 1 , "email" : "a@a.com 等 } 希望你能理解我,谢谢
  • @EsLaM 虽然不直接回答,但让我宣传一下我前段时间为 Laravel 创建的 ResponseBuilder 包,以规范和简化使用 L 编写的 API:github.com/MarcinOrlowski/laravel-api-response-builder

标签: php json laravel laravel-5


【解决方案1】:

更新(2021 年 2 月 9 日):如果适用,将模型序列化为 JSON 的最佳方法是使用 Eloquent's API Resources。这在您构建 RESTful API 时特别有用。


使用response()json() 方法。

$data = [
    "status" => "200",
    "details" => [
        "id": 1,
        "email": "a@a.a",
        "mobile": "",
        "source": "",
        "source_id": "",
        "message": "Bad Request : Already Logged In"            
    ]
];

return response()->json($data);

这将返回以下 JSON:

{
    "status": "200",
    "details":  { 
        "id": 1,
        "email": "a@a.a",
        "mobile": "",
        "source": "",
        "source_id": "",
        "message": "Bad Request : Already Logged In"
    }
}

【讨论】:

    【解决方案2】:
    Response(['status'=>'data','details'=>'data'], HTTP_OK);
    

    【讨论】:

    • 虽然此代码 sn-p 可能是解决方案,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    【解决方案3】:

    简单地返回数组:

    $data = [
        "status" => "200",
        "details" => [
            "id": 1,
            "email": "a@a.a",
            "mobile": "",
            "source": "",
            "source_id": "",
            "message": "Bad Request : Already Logged In"            
        ]
    ];
    
    return $data;
    

    它将被 Laravel 解析为 JSON 响应 automatically

    [..] 你也可以返回数组。框架会自动将数组转换为 JSON 响应

    【讨论】:

      【解决方案4】:

      只返回数组 json

      return response()->json(['status'=>200,'data'=>$products]);
      
      
      
      "status": 200,
          "data": [
              {
                  "id": 15,
                  "title": {
                      "en": "Someone’s sitting in the shade today because someone planted a tree a long time ago.",
                      "ar": "شخص ما يجلس في الظل اليوم لأن أحدهم زرع شجرة منذ زمن بعيد",
                      "ca": "Alguien está sentado a la sombra hoy porque alguien plantó un árbol hace mucho tiempo."
                  },
                  "slug": {
                      "en": "someone-s-sitting-in-the-shade-today-because-someone-planted-a-tree-a-long-time-ago",
                      "ar": "شخص-ما-يجلس-في-الظل-اليوم-لأن-أحدهم-زرع-شجرة-منذ-زمن-بعيد",
                      "ca": "alguien-esta-sentado-a-la-sombra-hoy-porque-alguien-planto-un-arbol-hace-mucho-tiempo"
                  },
                  "description": {
                      "en": "Someone’s sitting in the shade today because someone planted a tree a long time ago.",
                      "ar": "شخص ما يجلس في الظل اليوم لأن أحدهم زرع شجرة منذ زمن بعيد",
                      "ca": "Alguien está sentado a la sombra hoy porque alguien plantó un árbol hace mucho tiempo."
                  },
                  "created_at": "2021-03-15T18:31:02.000000Z",
                  "updated_at": "2021-03-15T18:31:02.000000Z"
              },
              {
                  "id": 14,
                  "title": {
                      "en": "Define success on your own terms, achieve it by your own rules, and build a life you’re proud to live.",
                      "ar": "حدد النجاح بشروطك الخاصة، وتحققه بقواعدك الخاصة، واصنع حياة تفخر بأن تعيشها.",
                      "ca": "Defina el éxito en sus propios términos, consígalo según sus propias reglas y construya una vida de la que se sienta orgulloso de vivir."
                  },
                  "slug": {
                      "en": "define-success-on-your-own-terms-achieve-it-by-your-own-rules-and-build-a-life-you-re-proud-to-live",
                      "ar": "حدد-النجاح-بشروطك-الخاصة-وتحققه-بقواعدك-الخاصة-واصنع-حياة-تفخر-بأن-تعيشها",
                      "ca": "defina-el-exito-en-sus-propios-terminos-consigalo-segun-sus-propias-reglas-y-construya-una-vida-de-la-que-se-sienta-orgulloso-de-vivir"
                  },
                  "description": {
                      "en": "Define success on your own terms, achieve it by your own rules, and build a life you’re proud to live.",
                      "ar": "حدد النجاح بشروطك الخاصة، وتحققه بقواعدك الخاصة، واصنع حياة تفخر بأن تعيشها.",
                      "ca": "Defina el éxito en sus propios términos, consígalo según sus propias reglas y construya una vida de la que se sienta orgulloso de vivir."
                  },
                  "created_at": "2021-03-15T18:31:02.000000Z",
                  "updated_at": "2021-03-15T18:31:02.000000Z"
              },
              {
                  "id": 13,
                  "title": {
                      "en": "Never give up. Today is hard, tomorrow will be worse, but the day after tomorrow will be sunshine.",
                      "ar": "لا تستسلم أبداً اليوم صعب، غدا سيكون أسوأ، لكن بعد غد سيكون شروق الشمس.",
                      "ca": "Nunca te rindas. Hoy es duro, mañana será peor, pero pasado mañana habrá sol."
                  },
                  "slug": {
                      "en": "never-give-up-today-is-hard-tomorrow-will-be-worse-but-the-day-after-tomorrow-will-be-sunshine",
                      "ar": "لا-تستسلم-أبدا-اليوم-صعب-غدا-سيكون-أسوأ-لكن-بعد-غد-سيكون-شروق-الشمس",
                      "ca": "nunca-te-rindas-hoy-es-duro-manana-sera-peor-pero-pasado-manana-habra-sol"
                  },
                  "description": {
                      "en": "Never give up. Today is hard, tomorrow will be worse, but the day after tomorrow will be sunshine.",
                      "ar": "لا تستسلم أبداً اليوم صعب، غدا سيكون أسوأ، لكن بعد غد سيكون شروق الشمس.",
                      "ca": "Nunca te rindas. Hoy es duro, mañana será peor, pero pasado mañana habrá sol."
                  },
                  "created_at": "2021-03-15T18:31:02.000000Z",
                  "updated_at": "2021-03-15T18:31:02.000000Z"
              }
      

      ]

      【讨论】:

        猜你喜欢
        • 2019-06-30
        • 2017-03-25
        • 2020-10-11
        • 2020-02-20
        • 1970-01-01
        • 2015-05-06
        • 2017-04-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多