1
votes

Is there any validation expression like unique: in Laravel that return true if value exist in database for the :attribute like. Have a look at email attribute:-

$data=[]
$rules= ['email': 'exist_in_database']
$validator=Validator::make($data,$rules);
if($validator->passes()){
//do something
}else{
//error
}

==>unique: return false if value exist

if no such validation exist that how to make custom validator by extending Validator for this problem? Please help

3

3 Answers

1
votes

Yes and the syntax for it is unique:table,column,except,idColumn

In your case,

$rules= ['email' => 'unique:users,email'];

For further docs, check this link.

0
votes

I use this to validate any unique field, in this case Email ID which belongs to USERS table:

 if (!empty($id)) {
     $rules['email'] = 'required|email|min:6|max:75|unique:users,email,' . $id . ',id,deleted_at,0000-00-00 00:00:00';
} 
else {
    $rules['email'] = 'required|email|min:6|max:75|unique:users,email,NULL,id,deleted_at,0000-00-00 00:00:00';
}
0
votes

Answering the question "How to create a new Validator". Here is how:

Validator::extend('validator_name', function ($attribute, $value, $parameters, $validator){

// whatever code you want here, I suggest you play with the parameters

// below there is an example of validation using regex
  return preg_match('/^[\pL\h]+$/u', $value);
});

To make this code work, create a ValidatorServiceProvider and put this code inside boot() function, then register the provider in your app.php like this:

App\Providers\ValidatorServiceProvider::class,