Laravel Json Response Not working as expected

前端 未结 3 1731
暖寄归人
暖寄归人 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: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);
    }
    

提交回复
热议问题