Validate jpg file - Laravel 5

Asked

Viewed 1,031 times

3

I’m trying to use the Validator to validate the upload file type but not sure if the syntax is correct

    $data=Input::all();

    $file  = $data["picture_url"]; 
    $rules = array('picture_url' => 'required|max:10000|mimes:jpg');

    $validator = Validator::make($file, $rules);

    if ($validator->fails()) {
        echo "Arquivo inválido";
    }else{

    }

because the following mistake is making

Errorexception in Factory.php line 91: Argument 1 passed to Illuminate Validation Factory::make() must be of the type array, Object Given, called in C: Users ssilva Documents wispot-manager vendor Laravel framework src Illuminate Support Facades Facade.php on line 219 and defined

Does anyone know how to solve?

2 answers

3


Here’s the problem. In Laravel, when you take an index of an input referring to an upload file, it returns an object from Symfony called Symfony\Component\HttpFoundation\File\UploadedFile\FilesBag (when you have more than one upload file) or Symfony\Component\HttpFoundation\File\UploadedFile.

In that case, you must pass the array containing the following pair ['nome_do_indice_do_input' => 'valor_do_indice'].

So instead of doing this:

$data = Input::all();

 $file  = $data["picture_url"];

Do so:

  $file  = Input::only('picture_url')

  Validator::make($file, $rules);

Thus, it will only pick up the index picture_url and return a array containing key and field value. Thus, the validation should work as expected.

You can also optionally keep your current code by changing only the line referring to the Validator::make, thus:

 Validator::make(['picture_url' => $file], $rules);
  • 1

    Yeah, it really worked! and I changed the Rules to $rules = array('picture_url' => 'required|image');

1

The $file passed as argument in Validator has to be an array to compare with $Rules, because the way you are using the variables you are not getting the file. you can do it this way;

$data = Input::all();
$rules = array('picture_url' => 'required|max:10000|mimes:jpg');
$validator = Validator::make($data, $rules);
  • do not believe that the problem is only by not using the Input::file because before I said I had done a test with the Input::file and only $data["picture_url"]; and they returned the same value, object Symfony as our friend up there said

  • I edited the answer, you’re right

  • 1

    @Silvioandorinha consider Miguel’s response as a complement. In some cases, the form he made may be simpler. For example, if you are validating more than one thing. What is not validated may also be in the array, no problem.

  • @Wallacemaxters...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.