Custom validation error message in Laravel

November 9th, 2022

validation in store() method

1st parameter is an array of rules for validation ['name of input' => 'rules']

2nd parameter is an array of error messages: ['key.rule' => 'Custom message!']

1public function store()
2{
3 // validation
4 $attributes = request()->validate([
5 'employee_id' => 'required|integer',
6 'content' => 'required',
7 'date' => 'required|date|before_or_equal:today',
8 'date_of_next_contact' => 'required|after_or_equal:today',
9 ], [
10 'employee_id.integer' => 'Please choose your contact.'
11 'content.required' => 'Please fill this in!'
12 ]);
13 
14 // store
15 
16 // return redirect
17 
18}

separate validation with Form Request

create request

1pa make:request StoreCommRequest

separate rules and messages function

1public function rules()
2{
3 return [
4 'employee_id' => 'required|integer',
5 'content' => 'required',
6 'date' => 'required|date|before_or_equal:today',
7 'date_of_next_contact' => 'required|after_or_equal:today',
8 ];
9}
10 
11public function messages()
12{
13 return [
14 'employee_id.integer' => 'Please choose your contact.'
15 'content.required' => 'Please fill this in!'
16 ];
17}
1public function store()
2{
3 // Retrieve the validated input data...from StoreCommRequest
4 $attributes = $request->validated();
5 
6 // store
7 
8 // return redirect
9 
10}