Laravel Json 响应未按预期工作

Laravel Json Response Not working as expected

响应对象为空时无法获得响应。当对象返回数据时完美运行。

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);
}

$associate 对象为空时无响应。 $associate 不为空时的响应:

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

我对状态代码 204 有同样的问题。 我相信这是在这里造成的。 Illuminate\Foundation\Application class 然后捕捉到这个并抛出一个 HttpException。

我认为最简单的解决方法是将控制器 return 改为以下内容:

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

返回空消息。 检查代码中的 status_code 以在前端显示消息。

如果使用路由模型绑定来查找记录的ID,会更容易。有关详细信息,请查看 https://laravel.com/docs/5.7/routing#route-model-binding

我认为下面的代码片段应该有效。

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

我重写了函数供大家参考。

顺便说一句。如果函数return只有一条记录,变量名一般用单数名词

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);
}