Laravel Form Request multiple validation rules of the same type

I have a form request validation file that checks if an input field is empty ('required')

and then if it exists in the database in a table 'table1'

.

I want to add a second existence rule to the same input field and return a message if the second validation rule fails:

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!'
        ];
}

      

Now only the second rule is in effect. Any ideas how? :)

Thank you all in advance!

+3


source to share


1 answer


In this situation, you can write your own validation rule. For example, let's create a CustomValidator class (put it in a folder like "App \ Services" or whatever 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've created a new rule called myexists

. This rule can take a couple of parameters, separated by commas, like this: "myexists: table1, searchfield1, table2, searchfield2 ..." I wrote a very simple example of this rule implementation, from which you can add some approach or other checks. ..

Then you must register your own validation rule in the AppServiceProvider in the method boot

(the string you put as the first parameter will be the name of the 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 method, enter the following code:

public function rules()
{
    $rules = [
        'id' => 'myexists:tableName1,field1,tableName2,field2',
    ];
    return $rules;
}

      

You can add a confirmation message for this rule, for example in the lang\en\validation.php

file'myexists' => 'Field :attribute must exists in all described tables.'

+1


source







All Articles