How to create custom validation method in laravel for server side validation
Before inserting any data into our database we must need to verify all data at server side.Laravel provide easy way to validate server side validation also we can create custom validation method for when we need to validate data that is already exist or not or validate date is grater than or not that such time we need to create custom method for validating those field.
Please follow below step to create custome validation method.
Step 1: Open your terminal and create laravel project.
In this first step open your terminal OR simply press Ctrl + Alt + T and add below code to your terminal to install laravel project.
composer create-project laravel/laravel --prefer-dist laravel-custome-validation
Step 2: Create blank database and configure your .env file and add below code to your terminal.
php artisan migrate
php artisan key:generate
Step 3: Follow below step to Configure validation file.
Create folder inside app directory Validator and create file CustomeValidator.php and add below line of code.
app/Validator/CustomeValidator.php
namespace App\Validator;
use Illuminate\Validation\Validator;
use Illuminate\Support\Facades\Input;
use Hash;
class CustomeValidator extends Validator
{
/**
* [validatecheckEmailExitForUser To check user email exit or not]
* @param [type] $attribute [description]
* @param [type] $value [description]
* @param [type] $parameters [description]
* @return [type] [description]
*/
public function validatecheckEmailExitForUser($attribute, $value, $parameters)
{
if (isset($parameters[0]) && !empty($parameters[0])) {
$count = \App\User::where("id", "!=", \Crypt::decrypt($parameters[0]))
->where("email", $value)
->count();
} else {
$count = \App\User::where("email", $value)->count();
}
if ($count === 0) {
return true;
} else {
return false;
}
}
}
Open your AppServiceProvider.php and add below line of code in boot method and import validator
and custom validation file
app/Providers/AppServiceProvider.php
namespace App\Providers;
use Validator;
use Illuminate\Support\ServiceProvider;
use App\Validator\CustomeValidator;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
$this->app->validator->resolver(function($translator, $data, $rules, $messages) {
return new CustomeValidator($translator, $data, $rules, $messages);
});
}
}
Here above file CustomeValidator.php we have added one method checkEmailExitForUser this custome method will check if user is already exist or not,also note that every validation method add prefix validate and after add your method name as we have added in CustomeValidator.php.
I have added sample code for how to add method during validation and i have added method checkEmailExitForUser for
email validation during user registration.
public function ApiUserregistration(Request $r){
$input = $r->all();
$rules = [
'name' => 'required',
'email' => 'required|email|checkEmailExitForUser',
'password' => 'required',
];
$message = [
'name.required' => "Name field is required.",
'email.required' => "Email field is required",
'email.check_email_exit_for_user' => "Email alredy exits.",
'password.required' => "Password field is required",
];
$validator = Validator::make($input,$rules,$message);
if ($validator->fails()) {
return app('App\Http\Controllers\Api\ApiCommanFunctionController')->sendError($validator->errors()->first(), $errorMessages = [], $code = 422);
}
$obj = new User;
$obj->name =$r->name;
$obj->email =$r->email;
$obj->password =\Hash::make($r->password);
$obj->save();
if ($obj !=null) {
return response()->json(['status' => 200,'msg'=>"User successfully register.",'data' => $obj ]);exit;
}else{
return response()->json(['status' => 204,'msg'=>"Somethinig is wrong or data not found",'data' => (object)[] ]);exit;
}
}