How to Force Formrequest Return JSON in Laravel 5.1

Laravel request service return json

You don't have to do it manually, it will automatically sends an errors response, which could be use like:

    @if ($errors->has())
<div class="alert alert-danger">
@foreach ($errors->all() as $error)
{{ $error }}<br>
@endforeach
</div>
@endif

OR

@if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> @endif

OR

Skip Request and do Validator::make() and in the end do:

return response($validatorObject->messages(), 500);

Laravel 5 Validation - Return as json / ajax

You can use $validator->messages() that returns an array which contains all the information about the validator, including errors. The json function takes the array and encodes it as a json string.

if ($validator->fails()) {    
return response()->json($validator->messages(), Response::HTTP_BAD_REQUEST);
}

Note: In case of validation errors, It's better not to return response code 200. You can use other status codes like 400 or Response::HTTP_BAD_REQUEST

laravel return json with error instead of redirection after validation FormRequest

The most common case you need a json response instead of redirection is in API usages. So, you will need to add the following header in your call

Content-Type: application/json

Otherwise, check this example on how to validate the request and handle the validation failure.

https://laravel.com/docs/6.x/validation#manually-creating-validators

¿How to create a custom FormRequest from normal Request?

If you really want to get an instance of your Form Requests, without resolving them from the IoC Container, you could use the createFrom method:

$firstRequest = StoreClientRequest::createFrom($request);

This will make sure it is filled with the same data as $request.



Related Topics



Leave a reply



Submit