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]);
}
}
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 ;)