Search code examples
jsonlaravelapiresponse

Want to remove attribute array in my response Laravel api


This is my code. I just want to remove attribute array from message because I’m not fetching error on my frontend on angular and andriod app.

public function createCountry(Request $coun)
{
    $validate = Validator::make($coun->all(), [
        'country_name' => 'required|unique:countries,country_name|regex:/^[a-zA-Z\s]+$/',
    ]);
    if ($validate->fails()) {
        return response()->json(['code' => 400, 'message' => $validate->errors()], 400);
    } else {
        $country = Country::create([
            'country_name' => $coun->input('country_name'),
        ]);
        return response()->json(['code' => 201, 'message' => 'Country Created Successfully',
            'object' => $country], 201);
    }
}

This is my response

{
    "code": 400,
    "message": {
        "country_name": [
            "The country name already exist.",
            "The country name format is invalid."
        ]
    }
}

Solution

  • If you're just looking to return the error messages without their keys, then you want to use the all() method available on the MessageBag object.

    public function createCountry(Request $coun)
    {
        $validate = Validator::make($coun->all(), [
            'country_name' => 'required|unique:countries,country_name|regex:/^[a-zA-Z\s]+$/',
        ]);
    
        if ($validate->fails()) {
            // Note the use of all() after calling the errors() method
            return response()->json(['code' => 400, 'message' => $validate->errors()->all()], 400);
        }
    
        $country = Country::create([
            'country_name' => $coun->input('country_name'),
        ]);
    
        return response()->json([
            'code' => 201, 'message' => 'Country Created Successfully',
            'object' => $country
        ], 201);
    }
    

    This will result in the keys being omitted from the response:

    {
        "code": 400,
        "message": [
            "The country name already exist.",
            "The country name format is invalid."
        ]
    }
    

    Update 1

    If you don't want the array brackets included for a single error message, then you could do the following:

    if ($validate->fails()) {
        $messages = $validate->errors()->count() > 1 ? $validate->errors()->all() : $validate->errors()->first();
        return response()->json(['code' => 400, 'message' => $messages], 400);
    }