Laravel is a powerful PHP framework that helps you to build a web application quickly. Laravel is very easy to use and maintain the codebase, I will advise using the latest version of laravel when building a new project.
Read Also : How to solve This page isn’t working HTTP ERROR 500 in Laravel
Today I will show how you can customize the laravel validator error and reused it when validating your requests and return a nice error message to the user.
Example functions
use Validatorpublic function example(Request $request){
$input = $request->all();
$rules = [
'first_name' => 'required',
'username' => 'required'
];
$validator = Validator::make($input, $rules);
if (validator->fails()){
return [
'message' => $validator->errors()
];
}
}
Now you have learned how to do your own customized message in your laravel applications. You can easily turn this function into a reusable function to avoid repeating the same code when you are validating another type of incoming request.
Separating the function to a reusable function
public function validate($input, $rules){
$validator = Validator::make($input, $rules);
if (validator->fails()){
return [
'message' => $validator->errors()
];
}
}
Reusing the function inside the example function
public function example(Request $request){
$input = $request->all();
$rules = [
'first_name' => 'required',
'username' => 'required'
];
$error = $this->validate($input, $rules);
if (error){
return $error;
}
}
Cool right, writing clean code is always good, and avoid repeating the same code in your functions.
Be first to comment