In every application, validating user input before executing further logic is essential. Laravel makes this simple with its validator methods. When working with APIs, we often need to customize Laravel request validation response to return errors in JSON format instead of the default error bag. This approach keeps validation logic separate from the main request handling and ensures consistent API responses.
Create Custom Validation Rule
Let’s take an example to return JSON data for validation request error or customize error response. Here, we will take user input and validate it using the Laravel request method.
To create a request class, open the terminal and enter the below command:
php artisan make:request UserStoreRequest
It will create a new file under the App\Http\Requests directory. Open the file and modify it as below:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
class UserStoreRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|min:8',
'c_password' => 'required|min:8|same:password',
];
}
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException(
reponse()->json([
'message' => 'Data Validation Failed',
'errors' => $validator->errors()
])''
);
}
}
Here, we have added some common validation rules like the name field is required, the email field is also required and must be email and password, and the confirm password must be the same.
Here, we have added failedValidation() method to handle error response. Normally if validation fails Laravel handles it as regular but this method will override the default error response logic as per our requirement.
Here, we have passed the validator instance as a parameter to get validation errors. It will throw an HTTP response exception with our custom response format. In this case, which is JSON.
Conclusion
This article created a validation request class for user inputs, and if validation fails it will return JSON containing errors.
For handling API responses, collections are often not enough and need to be converted into JSON. You can convert collection into JSON in Laravel using methods like toJson(), json(), or json_encode() for easy data handling in your applications.