Laravel Json Response Not working as expected

∥☆過路亽.° 提交于 2020-07-10 11:40:06

问题


Unable to get response while response object is empty. Works perfect when the object has data returned.

public function show($id)
{
    $associates = Associate::find_by_id($id);
    if(count($associates)<1)
    {
        $output = array('message' => 'No Records Found');
        $status = 204;

    }
    else{
        $output = array('message' => 'success','data'=>$associates);
        $status = 200;
    }
    return response()->json($output,$status);
}

There is no response when the $associate object is empty. Response when $associate is not empty:

{
"message": "success",
"data": [
    {
        "first_name": "xxx",
        "last_name": "xxx",
        "mobile": xxxxxxxxxx,
        "email": "xxxxxx@xxxxx",
        "city": "xxxxx",
        "state": "xxxxxx",
        "pincode": "xxxxx"
    }
  ]
}

回答1:


I had the same issue for status code 204 . I believe this is caused here. The Illuminate\Foundation\Application class is then catching this and throwing an HttpException.

I believe the simplest fix would be to make the controller return the following instead:

return Response::make("", 204);

Returning a empty message. check status_code in your code to display message in frontend .




回答2:


It will be easier if you use route model binding to find the ID of the record. For more information check https://laravel.com/docs/5.7/routing#route-model-binding.

I think the snippet below should work.

if ($associates) {
    $output = array('message' => 'success','data'=>$associates);
    $status = 200;
} else {
    $output = array('message' => 'No Records Found');
    $status = 204;
}



回答3:


I've rewrote the function for your reference.

BTW. If the function return only one record, use singular noun for variable name in general.

public function show($id)
{
    // Use find() instead of find_by_id()
    $associate = Associate::find($id);

    // $associate will be null if not matching any record.
    if (is_null($associate)) {

        // If $associate is null, return error message right away.
        return response()->json([
            'message' => 'No Records Found',
        ], 204);
    }

    // Or return matches data at the end.
    return response()->json([
        'message' => 'success',
        'data' => $associate,
    ], 204);
}


来源:https://stackoverflow.com/questions/53178145/laravel-json-response-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!