DEV Community

Debajyoti Das
Debajyoti Das

Posted on

Zip upload with validations in Laravel

Following code is for unzipping files, then validating and lastly saving in the database.

public function unzip_contents_gallery(Request $request)
    {
        try{
            $v = [];
            $allowed_exts = [
                'png',
                'jpeg',
                'jpg',
                'webp',
            ];
            $zip = new ZipArchive();
            $status = $zip->open($request->file("zip_gallery")->getRealPath());

            if ($status !== true) 
                throw new Exception('Un-supported zip archive');

            for($i=0; $i<$zip->count();$i++)
            {
                array_push($v, ['name' => $zip->getNameIndex($i)]);
                $ext_name_arr = explode('.', $zip->getNameIndex($i));
                if(!(in_array(end($ext_name_arr), $allowed_exts)))
                    throw new Exception('File not supprted!');
            } 
            $rules = [
                '*.name' => 'required|unique:galleries,gallery',
            ];
            $validator = Validator::make($v, $rules);
            if($validator->fails()) 
                throw new Exception(json_encode($validator->errors()->all()));
                // throw new Exception($validator->errors()->first());

            $storageDestinationPath = public_path('uploads/gallery_images');
            if (!\File::exists( $storageDestinationPath)) {
                \File::makeDirectory($storageDestinationPath, 0755, true);
            }
            $zip->extractTo($storageDestinationPath);
            $zip->close();
            for($i=0; $i<count($v);$i++)
            {
                Gallery::create([
                    'gallery' =>  $v[$i]
                ]);
            } 

            $msg = "File Upload Successfully";
            return redirect()->back()->withSuccess($msg);
        }
        catch(Exception $e)
        {
            return redirect()->back()->withErrors($e->getMessage());
        }
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)