0
votes

Yo! I am working on a form where I attach some image.

Form:

{{ Form::file('attachments[]', array('multiple')) }}

Validation:

$this->validate($response, array(
    'attachments' => 'required | mimes:jpeg,jpg,png',
));

I have also tried 'image' as validator rule but whenever I post the form with jpg image I get back errors:

The attachments must be a file of type: jpeg, jpg, png.

Working with Laravel 5.3

1

1 Answers

0
votes

Since you defined an input name of attachments[], attachments will be an array containing your file. If you only need to upload one file, you might want to rename your input name to be attachments, without the [] (or attachment would make more sense in that case). If you need to be able to upload multiple, you can build an iterator inside your Request-extending class that returns a set of rules covering each entry inside attachments[]

protected function attachments()
{
    $rules          = [];
    $postedValues   = $this->request->get('attachments');

    if(null == $postedValues) {
        return $rules;
    }

    // Let's create some rules!
    foreach($postedValues as $index => $value) {
        $rules["attachments.$index"] = 'required|mimes:jpeg,jpg,png';
    }
    /* Let's imagine we've uploaded 2 images. $rules would look like this:
        [
            'attachments.0' => 'required|mimes:jpeg,jpg,png',
            'attachments.1' => 'required|mimes:jpeg,jpg,png'
        ];
    */

    return $rules;
}

Then, you can just call that function inside rules() to merge the array returned from attachments with any other rules you might want to specify for that request:

public function rules()
{
    return array_merge($this->attachments(), [
       // Create any additional rules for your request here... 
    ]);
}

If you do not yet have a dedicated Request-extending class for your form, you can create one with the artisan cli by entering: php artisan make:request MyRequestName. A new request class will be created inside app\Http\Requests. That is the file where you would put the code above in. Next, you may just typehint this class inside the function signature of your controller endpoint:

public function myControllerEndpoint(MyRequestName $request)
{
    // Do your logic... (if your code gets here, all rules inside MyRequestName are met, yay!)
}