0

I have a ServiceProvider:

 namespace App\Providers;

    use Illuminate\Support\ServiceProvider;

    use \Validator;

    use App\Services\CustomValidator;


    class AppServiceProvider extends ServiceProvider
    {
      public function boot() {
        Validator::extend('firstname_fail', 'App\Services\CustomValidator@fullnameFailValidate');
        Validator::extend('lastname_fail', 'App\Services\CustomValidator@lastnameFailValidate');
        Validator::extend('hotel_fail', 'App\Services\CustomValidator@hotelFailValidate');
        Validator::extend('city_fail', 'App\Services\CustomValidator@cityFailValidate');
   }

}

I have a model Tourist, which has such attributes: firstname, lastname, hotel, city. And there can be added some other (many) attributes.

(I know how to get all field names from Tourist model: $array = Schema::getColumnListing('tourists'); )

So my question is how to make a dynamic creation of:

Validator::extend('fieldname_fail', "App\Services\CustomValidator@fieldnameFailValidator')

inside the boot() method?

I tried to use magic _call method, but didn't succeed...

Any help appreciated!:)

1
  • I can smell this over the network! So much magic is just bad, when you come back after 30 days you will have no clue how this part of app works. Commented Jul 21, 2017 at 18:01

1 Answer 1

1

If I understand correctly you need something like this.

  1. Iterate over table fields (model attributes);
  2. Extend validator for each field (model attribute).

Here is a code example:

foreach (Schema::getColumnListing('tourists') as $attribute) {
    Validator::extend("{$attribute}_fail", "App\Services\CustomValidator@{$attribute}FailValidator");
}
Sign up to request clarification or add additional context in comments.

2 Comments

you a great! It is so simple that I feel studid not figuring it out.
you made a mistake though: "${$attribute}_fail" shuold be "{$attribute}_fail" and "${$attribute}FailValidator" should be "{$attribute}FailValidator". Please, correct your answer and I accept it as "right":)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.