Jesús V.
Jesús V.

Reputation: 129

Forcing json responses for API not working on laravel 8

I'm building an small API with passport auth with laravel 8 and also using FormRequest classes for validations requests.

Problem is that when an error occurrs, API doesn't respond with JSON, it just returns nothing.

I've already created a new Middleware to handle only json responses by adding this $request->headers->set('Accept', 'application/json');on the handle method, but it doesn't seem to be working!

Does anyone knows if I'm missing something?

Upvotes: 0

Views: 1366

Answers (1)

Omar Villafuerte
Omar Villafuerte

Reputation: 69

The response helper can be used to generate other types of response instances. The json method will automatically set the Content-Type header to application/json

return response()->json([
    'success' => true,
    'message' => 'Hello world',
]);

I show an example applied to a validation

public function register(Request $request)
{
    $validator = Validator::make($request->all(), [
        'name' => 'required',
        'email' => 'required|email'
    ]);
   
    if($validator->fails()) {
        return response()->json([
            'success' => false,
            'message' => $validator->errors()
        ], 422);
    }

    # other instructions ...
}

Upvotes: 2

Related Questions