Search code examples
phplaravelvalidationlaravel-5.3

how to validate a field that can be a digit or Url or a file to upload in laravel


I have a field named Photo that coming from a form.

In the first step that field must be required to send and then can be a digit number Or a Url Or a new uploaded photo file.

I know how can I use laravel validation rules to check where it could be digit. like this:

'photo' => 'required|digit'

But I do not know how can I check if photo was not a digit is url or uploaded file.

Of course if I wrote like this :

'photo' => 'required|digit|url|file'

In this case laravel give me error if photo is a digit and is not a url.

Can anyone help me to solve this?


Solution

  • You can do it like this:

    App/Http/Requests/FormRequest.php

    public function rules()
    {
       if(is_numeric($this->photo)) {
          $validation = 'digit';
       } else if (!filter_var($this->photo, FILTER_VALIDATE_URL) === false) {
          $validation = 'url';
       } else {
          $validation = 'file';
       }
    
     return [
          'photo' => 'required|' . $validation
        ];
     }
    

    Note: Not tested, but it should give you the basic idea.