Laravel Json Response Not working as expected

前端 未结 3 1724
暖寄归人
暖寄归人 2021-01-28 19:09

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

public function show($id)
{
    $associates = Associate::         


        
相关标签:
3条回答
  • 2021-01-28 19:38

    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 .

    0 讨论(0)
  • 2021-01-28 19:46

    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);
    }
    
    0 讨论(0)
  • 2021-01-28 19:49

    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;
    }
    
    0 讨论(0)
提交回复
热议问题