0
votes

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. - Kyslik

1 Answers

1
votes

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");
}