Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Zip Laravel Package

zanysoft/laravel-zip

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require zanysoft/laravel-zip
    

    Add the service provider to config/app.php:

    ZanySoft\Zip\ZipServiceProvider::class,
    

    Optionally, register the facade for convenience:

    'Zip' => ZanySoft\Zip\Facades\Zip::class,
    
  2. First Use Case: Create a zip file and add a file to it:

    use Zip;
    
    $zip = Zip::open('path/to/output.zip', 'w');
    $zip->add('path/to/source/file.txt');
    $zip->close();
    

Where to Look First

  • Documentation: The GitHub README provides basic usage examples.
  • Facade: Use Zip::open() to start working with zip files.
  • Methods: Key methods include add(), addFiles(), extract(), and close().

Implementation Patterns

Common Workflows

1. Creating and Populating a Zip File

$zip = Zip::open('backup.zip', 'w');
$zip->addFiles(['file1.txt', 'file2.txt', 'folder/*']);
$zip->close();

2. Extracting Zip Contents

$zip = Zip::open('backup.zip', 'r');
$zip->extract('path/to/destination');
$zip->close();

3. Adding Files with Custom Paths

$zip = Zip::open('archive.zip', 'w');
$zip->add('file.txt', 'custom/path/in/zip/file.txt');
$zip->close();

4. Streaming Large Files

Use Zip::stream() to handle large files without loading them entirely into memory:

$zip = Zip::stream('large_archive.zip', 'w');
$zip->add('huge_file.log');
$zip->close();

5. Integration with Laravel Storage

Combine with Laravel’s filesystem to handle cloud storage (e.g., S3):

use Storage;

$zip = Zip::open(storage_path('app/backup.zip'), 'w');
$zip->add(Storage::disk('s3')->path('file.txt'));
$zip->close();

6. Automating Backups

Use Laravel’s scheduling to run zip operations periodically:

// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
    $schedule->command('backup:create')->daily();
}

Integration Tips

  • Laravel Events: Trigger zip operations on events (e.g., job.failed):

    event(new JobFailed($job, $exception));
    Zip::open('logs/failed_jobs.zip', 'w')->add(storage_path('logs/laravel.log'));
    
  • API Responses: Serve zip files directly in API responses:

    return response()->download(storage_path('app/export.zip'))
        ->header('Content-Type', 'application/zip');
    
  • Queue Jobs: Offload zip creation to a queue for long-running tasks:

    ZipJob::dispatch('large_archive.zip', ['file1.log', 'file2.log']);
    

Gotchas and Tips

Pitfalls

  1. Memory Limits:

    • Large files may hit PHP’s memory_limit. Use Zip::stream() for big archives.
    • Configure php.ini or set ini_set('memory_limit', '512M') temporarily.
  2. File Paths:

    • Ensure paths are absolute or relative to the script’s working directory. Use realpath() for clarity:
      $zip->add(realpath('path/to/file.txt'));
      
  3. Zip Modes:

    • 'w' (write) overwrites existing files. Use 'a' (append) to add to existing zips:
      $zip = Zip::open('archive.zip', 'a');
      
  4. Permissions:

    • PHP must have write permissions for the output directory. Use storage_path() for Laravel’s storage folder.
  5. Nested Directories:

    • addFiles() does not recursively add directories by default. Use Zip::addDirectory() or glob patterns:
      $zip->addFiles(['folder/**/*']);
      

Debugging

  • Check Zip Status: Use Zip::getStatus() to debug errors:

    $zip = Zip::open('file.zip', 'w');
    if ($zip->getStatus() !== true) {
        throw new \RuntimeException('Failed to create zip: ' . $zip->getStatusMessage());
    }
    
  • Log Errors: Enable Laravel’s logging to capture zip-related exceptions:

    try {
        $zip->extract('destination');
    } catch (\Exception $e) {
        Log::error('Zip extraction failed: ' . $e->getMessage());
    }
    

Tips

  1. Compression Levels: Adjust compression for balance between speed and size:

    $zip = Zip::open('compressed.zip', 'w', ZipArchive::CM_DEFLATE, 9); // Max compression
    
  2. Exclude Files: Use Zip::addFiles() with a glob pattern to exclude files:

    $zip->addFiles(['*.txt', '!temp/*.tmp']); // Exclude temp files
    
  3. Facade vs. Class: Prefer the facade (Zip::open()) for simplicity in controllers/blades. Use the class (new \ZanySoft\Zip\Zip()) in services for dependency injection.

  4. Testing: Mock zip operations in tests using Laravel’s Zip facade:

    $this->partialMock(Zip::class, 'open')->willReturn($mockZip);
    
  5. Custom Naming: Use Zip::setName() to rename files when adding:

    $zip->add('old_name.txt', 'new_name.txt');
    
  6. Laravel Mix: Integrate with Laravel Mix for frontend asset zipping:

    // mix.js
    mix.js('resources/js/app.js', 'public/js')
        .then(() => {
            Zip::open('public/assets.zip', 'w')->add('public/js/app.js');
        });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager