Framework: Laravel 5.7.27 (PHP 7.2.10 )

There are several methods in which validation is performed on the server through the explicit designation of the request class: public function store(PostRequest $request)

The PostRequest.php file PostRequest.php validation rules:

 public function rules() { return [ 'title' => 'required|min:10', 'text' => 'required|min:10', 'image' => 'required|file|image', ]; } 

In all cases, image validation is required rule, but in one method it is not needed, how can I prevent it?

  • Get the array and delete the key. - u_mulder 2:41 pm
  • It is impossible to intercept the request, it is sent to this controller and it sees the Request type as an argument, it immediately calls on it to catch validation errors - LazyTechwork
  • If rules immediately in the model, then the PostRequest object itself is available to you. Check out something from him. I understand that he should have an id . Depending on the presence of id return one or another array of rules. - u_mulder 2:53 pm

2 answers 2

I think it would be best to create a separate FormRequest for this method and set validation rules in it:

 class MethodRequest extends PostRequest { public function rules() { $rules = parent::rules(); $rules['image'] = 'nullable|file|image'; return $rules; } } 

And accordingly use it in the controller:

 public function method(MethodRequest $request) 

    Decided crutch. PostRequest.php :

     public function rules() { $rules = [ 'title' => 'required|min:10', 'text' => 'required|min:10', ]; if(!$this->request->has('id')) $rules['image'] = 'required|file|image|max:2048'; return $rules; } 

    If there is no input[name=id] in $request , then add an image check to the array with rules. You could also send input[type=hidden] with form names.