put($path . '/' .$file->getClientOriginalName(), $file->getContent()); return File::query()->updateOrCreate([ 'link' => url('/storage/') . '/' . $path . '/' .$file->getClientOriginalName(), 'path' => $path . '/' .$file->getClientOriginalName(), 'user_id' => auth()->user()->id, 'original_name' => $file->getClientOriginalName(), 'mime_type' => $file->getClientMimeType(), ]); } /** * @param string $path * @param string $archiveName * @param int|null $userId * @return File * @throws Exception */ public function createZipArchive(string $path, string $archiveName, int $userId = null): File { if (!($tempFile = tempnam(sys_get_temp_dir(), Str::random()))) { throw new Exception('Cant create temporary file!'); } $zip = new ZipArchive(); $fullPath = storage_path('app/public/' . $path); $zip->open($tempFile, ZipArchive::CREATE | ZipArchive::OVERWRITE); $files = new RecursiveIteratorIterator( new \RecursiveDirectoryIterator($fullPath), RecursiveIteratorIterator::LEAVES_ONLY ); foreach ($files as $file) { if(!$file->isDir()) { // Get real and relative path for current file $filePath = $file->getRealPath(); $relativePath = substr($filePath, strlen($fullPath) + 1); // Add current file to archive $zip->addFile($filePath, $relativePath); } } $zip->close(); $fileModel = File::query()->updateOrCreate([ 'link' => url('/storage/') . '/' . Str::replace('/tmp', '', $path) . '/' .$archiveName, 'path' => $path . '/' .$archiveName, 'user_id' => $userId ?? auth()->user()->id, 'original_name' => $archiveName, 'mime_type' => 'application/zip', ]); $contents = file_get_contents($tempFile); Storage::disk('public')->put($path . '/../' .$archiveName, $contents); unlink($tempFile); return $fileModel; } }