Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating multiple files in array

I need to validate multiple uploaded files, making sure they are of a specific type and under 2048kb. The below doesn't appear to check all files in the array 'files' and just presumes the posted files of invalid mime type as it seems to be checking the array object and not its contents.

public function fileUpload(Request $request)
    {

       $validator = Validator::make($request->all(), [
            'files' => 'required|mimes:jpeg,jpg,png',
        ]);

        if ($validator->fails())
        {
            return response()->json(array(
                'success' => false,
                'errors' => $validator->getMessageBag()->toArray()

            ), 400);             }

}
like image 605
LaserBeak Avatar asked Jul 12 '16 10:07

LaserBeak


3 Answers

You can validate files array like any input array in Laravel 5.2. This feature is new in Laravel 5.2.

$input_data = $request->all();

$validator = Validator::make(
    $input_data, [
    'image_file.*' => 'required|mimes:jpg,jpeg,png,bmp|max:20000'
    ],[
        'image_file.*.required' => 'Please upload an image',
        'image_file.*.mimes' => 'Only jpeg,png and bmp images are allowed',
        'image_file.*.max' => 'Sorry! Maximum allowed size for an image is 20MB',
    ]
);

if ($validator->fails()) {
    // Validation error.. 
}
like image 139
im_tsm Avatar answered Nov 19 '22 16:11

im_tsm


Please try this:

public function fileUpload(Request $request) {
    $rules = [];
    $files = count($this->input('files')) - 1;
    foreach(range(0, $files) as $index) {
        $rules['files.' . $index] = 'required|mimes:png,jpeg,jpg,gif|max:2048';
    }

    $validator = Validator::make($request->all() , $rules);

    if ($validator->fails()) {
        return response()->json(array(
            'success' => false,
            'errors' => $validator->getMessageBag()->toArray()
        ) , 400);
    }
}
like image 21
Ismail RBOUH Avatar answered Nov 19 '22 17:11

Ismail RBOUH


we can also make a request and validate it.

    php artisan make:request SaveMultipleImages

here is the code for request

namespace App\Http\Requests;

use App\Core\Settings\Settings;
use Illuminate\Foundation\Http\FormRequest;

class SaveMultipleImages extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
    public function rules()
    {

        return ['files.*' => "mimes:jpg,png,jpeg|max:20000"];
    }
}

and then in controller

public function uploadImage(SaveMultipleImages $request) {

     dd($request->all()['files']);
}
like image 4
rameezmeans Avatar answered Nov 19 '22 17:11

rameezmeans