@filiberto
In Laravel, you can set a custom validation message by using the messages()
method in your controller or form request class.
Option 1: Using the messages()
method in the controller
- First, create a new rule in your controller using the Validator facade. For example:
use IlluminateSupportFacadesValidator;
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|min:8',
]);
if ($validator->fails()) {
return redirect('form')
->withErrors($validator)
->withInput();
}
// Validation passed, continue with the rest of your code
}
- To set custom validation messages, add the messages() method after defining the rules. For example:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|min:8',
]);
$validator->messages()->add([
'email.required' => 'The email field is required.',
'password.min' => 'The password must be at least 8 characters.',
]);
if ($validator->fails()) {
return redirect('form')
->withErrors($validator)
->withInput();
}
// Validation passed, continue with the rest of your code
}
Option 2: Using a form request class
- Create a new form request class using the make:request Artisan command. For example:
php artisan make:request MyFormRequest
- Open the newly created MyFormRequest.php file and update the rules() method with your validation rules. For example:
public function rules()
{
return [
'email' => 'required|email',
'password' => 'required|min:8',
];
}
- To set custom validation messages, add the messages() method in the MyFormRequest class. For example:
public function messages()
{
return [
'email.required' => 'The email field is required.',
'password.min' => 'The password must be at least 8 characters.',
];
}
- In your controller, type-hint the MyFormRequest class in your store() method. For example:
use AppHttpRequestsMyFormRequest;
public function store(MyFormRequest $request)
{
// Validation passed, continue with the rest of your code
}
By following these steps, you can set custom validation messages in Laravel.