dimanche 3 avril 2016

Laravel 5.2 - extending the Validator class

ReflectionException in Route.php line 270:

Class App\Http\Requests\FooRequest does not exist

This is the error I get when trying to use extensions of the native Validator and Request classes. This is what I did:

  1. Extend native Illuminate\Validation\Validator:

    class MyCustomValidator extends Validator {
    
        //override some functions here
    
    }
    
    
  2. Use MyCustomValidator in an abstract extension of native App\Http\Requests\Request:

    abstract class MyCustomRequest extends Request {
    
        //Override native method by injecting the extending validator
        protected function formatErrors( MyCustomValidator $validator )
        {
            return $validator->getMessageBag()->toArray();
        }
    }
    
    
  3. Extend MyCustomRequest with concrete class:

    class FooRequest extends MyCustomRequest
    {
    
        public function authorize()
        {
            return true;
        }
    
    
        public function rules()
        {
            return [
                // rules go here
            ];
        }
    }
    
    
  4. Use the FooRequest in a controller method:

    public function store(FooRequest $request) {
        //use the request and persist
    }
    
    

I am guessing I am lacking a required facade, provider, or container binding. I'm still learning these topics and don't understand them well enough to know a good next step.

References:

  • Custom validator in Laravel 5 - I followed the answer, but still got the same error. I want to know if this is is even remotely related to my problem before troubleshooting what I tried here.

  • Extending Custom Validation-Class - Problem looks similar, answer suggests using Validator::extend, which I know can be done in AppServiceProvider, but ideally my code should be in its own vendor package. Again, not sure if relevant.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire