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
PHP 7: Missing Vcruntime140.Dll
JSON_Encode/JSON_Decode - Returns Stdclass Instead of Array in PHP
Cannot Pass Null Argument When Using Type Hinting
Only Variables Should Be Passed by Reference In... on Line 13 Fail
How to Manually Return or Throw a Validation Error/Exception in Laravel
Place PHP Results Inside HTML Page
Setting Element of Array from Twig
Ajax/PHP - How to Get Posted Data to Load into a Modal on the Same Page
Php: How to Get a List of Classes That Implement Certain Interface
Printing to Pos Printer from PHP
How to Get Values of Xml Elements
Image Upload Storage Strategies
Efficient PHP Auto-Loading and Naming Strategies
PHP "Pretty Print" JSON_Encode
Php: Possible to Automatically Get All Posted Data and Multiple Checkbox Unchecked