You can create a request class that will be responsible for this, how?
Follow the Laravel documentation link: link
Example:
Your controller will have a method of creating a new user.
public function createUser(UserRequest $request){
// logica para criar o usuário
}
* Note, instead of using the default Request $request
, you create a class, which you modify as you wish, in it you pass the required error messages and fields.
How to create a class Request
?
use the artisan command: php artisan make:request NomeDaRequest
, by default it will be created in the request/
folder just look in your IDE you will find.
Within this new Request class, you have 2 methods that you will use to send field error messages and the fields called required, they are rules()
and messages()
. The rules()
it checks the required fields and messages()
displays the error messages.
public function messages(){
return [
'title.required' => 'A title is required',
'body.required' => 'A message is required',
];
}
public function rules(){
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}