Reputation: 2002
I have a Form Request Validation file, which checks is an input field not empty ('required')
and then if it's value exists in the database in table 'table1'
.
I want to add a 2nd exist rule to the same input field, and return a message if 2nd exist validation rule is not met:
public function rules()
{
return [
'tour' => 'required|exists:table1,id|//another exists: table2, id//'
];
}
public function messages()
{
return [
'tour.required' => 'Message 1!',
'tour.exists:table1,id' => 'Message 2!',
'tour.//another exists: table2, id//' => 'Message 3!'
];
}
Right now only 2nd rule works. Any ideas how-to?:)
thank you all in advance!
Upvotes: 3
Views: 1755
Reputation: 541
In this situation you can write your custom validation rule. For example, let create a class called CustomValidator (place him in folder like 'App\Services' or another that you want).
CustomValidator.php
namespace App\Services;
class CustomValidator {
public function myexistsValidate($attribute, $value, $parameters, $validator) {
for ($i = 0; $i < count($parameters); $i += 2) {
$count = \DB::table($parameters[$i])->where($parameters[$i + 1], $value)->count();
if (!$count) {
return false;
}
}
return true;
}
}
We created a new rule called myexists
. This rule can accept pair of paramaters divided by commas lile this: 'myexists:table1,searchfield1,table2,searchfield2...'`
I wrote very simple example of implementation of this rule, ofc you can add some approach or another validations...
Next you must register your own validation rule in AppServiceProvider in method boot
(string that you place as a first parameter will be a name of new rule):
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use \Validator;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Validator::extend('myexists', 'App\Services\CustomValidator@myexistsValidate');
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
Next in your FormRequest place code like this:
public function rules()
{
$rules = [
'id' => 'myexists:tableName1,field1,tableName2,field2',
];
return $rules;
}
You can add a validation message for this rule, for example in your lang\en\validation.php
file 'myexists' => 'Field :attribute must exists in all described tables.'
Upvotes: 1