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

Temporary Directory Laravel Package

spatie/temporary-directory

Create, use, and automatically clean up temporary directories in PHP. Spatie TemporaryDirectory makes it easy to generate a temp folder (in your system temp path), build file paths inside it, and delete everything when you’re done.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

Install via Composer:

composer require spatie/temporary-directory

First Use Case: Processing Uploads

use Spatie\TemporaryDirectory\TemporaryDirectory;

$tempDir = TemporaryDirectory::make()->create();

// Store files in temp directory
file_put_contents($tempDir->path('upload.csv'), $csvData);

// Process files (e.g., with Laravel's Filesystem)
$processed = Storage::disk('local')->exists($tempDir->path('upload.csv'));

// Cleanup automatically
unset($tempDir); // Triggers deletion via deleteWhenDestroyed()

Key Starting Points:

  • TemporaryDirectory::make() - Static factory method
  • $tempDir->path('subdir/file.txt') - Generate absolute paths
  • deleteWhenDestroyed() - Enable automatic cleanup

Implementation Patterns

Common Workflows

1. File Processing Pipeline

$tempDir = TemporaryDirectory::make()
    ->location(storage_path('app/temp'))
    ->permission(0755)
    ->create();

try {
    // 1. Write input
    file_put_contents($tempDir->path('input.json'), $request->json());

    // 2. Process with external tool
    $output = shell_exec("some-process {$tempDir->path('input.json')}");

    // 3. Store results
    file_put_contents($tempDir->path('output.json'), $output);

    // 4. Return path for download
    return response()->download($tempDir->path('output.json'));
} finally {
    $tempDir->delete(); // Explicit cleanup
}

2. Testing with Isolated Filesystem

public function test_file_processing()
{
    $tempDir = TemporaryDirectory::make()
        ->deleteWhenDestroyed()
        ->create();

    // Write test file
    file_put_contents($tempDir->path('test.csv'), 'data');

    // Assert processing works
    $this->assertTrue(file_exists($tempDir->path('test.csv')));

    // Test cleanup
    unset($tempDir);
    $this->assertFalse(file_exists($tempDir->getPath()));
}

3. Custom Location with Laravel Storage

$tempDir = TemporaryDirectory::make(storage_path('framework/temp'))
    ->name('laravel-process')
    ->force() // Overwrite if exists
    ->create();

// Use with Laravel Filesystem
Storage::disk('local')->put($tempDir->path('config.json'), $config);

Integration Tips

With Laravel Queues:

public function handle()
{
    $tempDir = TemporaryDirectory::make()
        ->deleteWhenDestroyed()
        ->create();

    // Process large file
    $this->processLargeFile($tempDir->path('input.pdf'));

    // Store results in DB with path
    $this->storeResult($tempDir->path('output.pdf'));
}

With Laravel Artisan Commands:

protected $tempDir;

protected function setup()
{
    $this->tempDir = TemporaryDirectory::make()
        ->location(sys_get_temp_dir())
        ->create();
}

protected function tearDown(): void
{
    $this->tempDir->delete();
}

Gotchas and Tips

Common Pitfalls

  1. Permission Issues

    • Default 0777 may cause problems on shared hosting
    • Solution: Explicitly set permissions:
      ->permission(0755)
      
  2. Race Conditions

    • When using force() with named directories
    • Solution: Use UUIDs or timestamps:
      ->name('temp-'.Str::uuid())
      
  3. Memory Leaks

    • Objects not properly unset when using deleteWhenDestroyed()
    • Solution: Explicitly unset or use context managers:
      $tempDir = TemporaryDirectory::make()->create();
      try {
          // Work
      } finally {
          unset($tempDir);
      }
      
  4. Path Resolution

    • path() returns absolute paths - verify with:
      $this->assertStringStartsWith(sys_get_temp_dir(), $tempDir->path('file'));
      

Debugging Tips

Verify Directory Exists:

if (!$tempDir->exists()) {
    throw new \RuntimeException("Temporary directory not created");
}

Check Cleanup:

$tempDir->delete();
$this->assertFalse(file_exists($tempDir->getPath()), "Directory not deleted");

Extension Points

  1. Custom Cleanup Logic

    $tempDir = TemporaryDirectory::make()->create();
    $tempDir->onDelete(function ($path) {
        // Custom cleanup (e.g., log deletion)
        Log::info("Deleted temp dir: {$path}");
    });
    
  2. Subclassing for Domain-Specific Needs

    class UploadTemporaryDirectory extends TemporaryDirectory
    {
        public function __construct()
        {
            parent::__construct(storage_path('app/uploads/temp'));
        }
    
        public function create(): self
        {
            return $this->permission(0750)->create();
        }
    }
    
  3. Testing Edge Cases

    // Test directory creation under heavy load
    $tempDirs = collect(range(1, 100))->map(fn($i) =>
        TemporaryDirectory::make()->name("test-{$i}")->create()
    );
    
    // Verify all created
    $tempDirs->each(fn($dir) => $this->assertTrue($dir->exists()));
    
    // Cleanup
    $tempDirs->each(fn($dir) => $dir->delete());
    

Configuration Quirks

  1. Windows Path Handling

    • Use forward slashes in paths for cross-platform compatibility:
      $tempDir->path('subdir/file.txt') // Works on both Windows/Linux
      
  2. SELinux Contexts

    • On systems with SELinux, you may need to adjust permissions:
      ->permission(0777)
      ->create()
      ->chmod(0755); // Additional chmod if needed
      
  3. Large Files

    • For files >2GB, consider:
      $tempDir = TemporaryDirectory::make()
          ->location(sys_get_temp_dir())
          ->create();
      
      // Use stream processing instead of loading entire file
      

Performance Considerations

  1. Directory Creation Overhead

    • Batch operations:
      $tempDirs = collect(range(1, 10))->map(fn($i) =>
          TemporaryDirectory::make()->name("batch-{$i}")->create()
      );
      
  2. Memory Management

    • For long-running processes, explicitly delete when done:
      $tempDir = TemporaryDirectory::make()->create();
      // ... long process ...
      $tempDir->delete(); // Force cleanup
      
  3. Filesystem Iterator Warning

    • The package uses FilesystemIterator which may be slow on very large directories (>100K files)
    • Solution: Implement custom cleanup for known file patterns

```markdown
### Laravel-Specific Tips

1. **Using with Laravel Filesystem**
```php
$tempDir = TemporaryDirectory::make(storage_path('app/temp'))->create();
Storage::disk('local')->put($tempDir->path('file.json'), $data);
  1. Queue Job Pattern
public function handle()
{
    $tempDir = TemporaryDirectory::make()
        ->deleteWhenDestroyed()
        ->create();

    // Process with Laravel's filesystem
    $this->processWithStorage($tempDir->path('input.csv'));

    // Store result path in DB
    Result::create([
        'path' => $tempDir->path('output.json'),
        'status' => 'processing'
    ]);
}
  1. Artisan Command with Temp Files
protected $tempDir;

protected function handle()
{
    $this->tempDir = TemporaryDirectory::make()
        ->location(sys_get_temp_dir())
        ->create();

    // Command logic using $this->tempDir
}

protected function tearDown(): void
{
    $this->tempDir->delete();
}
  1. Testing with Temporary Directories
public function test_file_upload_processing()
{
    $tempDir = TemporaryDirectory::make()
        ->deleteWhenDestroyed()
        ->create();

    Storage::fake('local');
    Storage::disk('local')->put($tempDir->path('test.pdf'), $pdfContent);

    $this->assertTrue(
        Storage::disk('local')->exists($tempDir->path('test.pdf'))
    );

    unset($tempDir);
    $this->assertFalse(
        Storage::disk('local')->exists($tempDir->getPath())
    );
}
  1. Service Container Binding
// In a service provider
$this->app->bind(TemporaryDirectory::class, function ($app) {
    return TemporaryDirectory::make(storage_path('app/temp'))
        ->permission(0750)
        ->deleteWhenDestroyed();
});
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony