Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mehalubozo's avatar

API Controller gives page response

Hi,

I created a controller that returns all my users. The api endpoint is working fine. When I create a user I also return the created user in json, all good. But when there is a validation error I get a normal page back.

Here is my code

class UsersController extends ApiController
{
    public function store(UserRequest $request)
    {
        $user = User::create($request->all());

        return response()->json(['user' => $user]);
    }
}

Any idea why this is going wrong?

0 likes
1 reply
bobbybouwmann's avatar
Level 88

Well Laravel will always return json here before you tell it to return json. However the validation will only be returned as json whenever Laravel knows you're doing an ajax request or json request. You can tell Laravel that by adding the following header in your request

`Accept` => 'application/json`,

So in your frontend or other tool you use to call the api url you should pass in this header and you will get a json response back from the validation ;)

Please or to participate in this conversation.