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

Start by installing the package via Composer:

composer require spatie/temporary-directory

This package solves the common problem of safely managing temporary directories in CLI scripts, console commands, or background jobs. The simplest use case is creating, using, and cleaning up temporary files in /tmp (or your system's temp directory) without worrying about leftover artifacts. Get started with:

use Spatie\TemporaryDirectory\TemporaryDirectory;

$tempDir = (new TemporaryDirectory())->create();

// Write something
file_put_contents($tempDir->path('data.json'), json_encode(['status' => 'ok']));

// Clean up
$tempDir->delete();

The most common first use case is processing large or sensitive intermediate data (e.g., file conversions, caching, test fixtures) where cleanup is non-negotiable.

Implementation Patterns

  • Builder-style chaining: Use method chaining for clarity and configuration before creation:
    (new TemporaryDirectory('/custom/path'))
        ->name('my-job-'.uniqid())
        ->permission(0750)
        ->create();
    
  • Automatic cleanup with deleteWhenDestroyed(): Wrap usage in a function or scope and let PHP’s GC handle deletion:
    public function process(User $user): void
    {
        $dir = (new TemporaryDirectory())->deleteWhenDestroyed()->create();
    
        // Build temp files...
        $this->generateReport($dir->path('report.pdf'));
    
        // No manual delete needed!
    }
    
  • Static factory make() for brevity:
    $dir = TemporaryDirectory::make();
    
  • Safe re-use in tests or batch jobs: Combine empty() for resets without full teardown:
    $dir->empty(); // wipes contents, keeps directory
    $dir->path('new-output.csv'); // safe to use again
    
  • Integration with Laravel commands: Use in handle() to ensure temp directories don’t persist across runs:
    $tmp = TemporaryDirectory::make(storage_path('app/temp'));
    $tmp->create();
    // ... process
    $tmp->delete();
    

Gotchas and Tips

  • name() without force() throws on conflict: If you specify a custom name, the package throws an exception if the directory already exists. Use ->force() to overwrite — but do so only when safe (e.g., names include timestamps or UUIDs).
  • Permissions are applied at creation only: Setting ->permission() after create() won’t affect existing directories. Always chain it before create().
  • getName() is available but fragile: Added in v2.3.0, getName() returns just the directory name — but relies on internal path parsing. Don’t assume the name matches your name() input if it was auto-generated (e.g., timestamp).
  • Delete failures on lock/broken symlinks: Older versions had edge-case issues (fixed in 2.2.1 and 2.3.1) with broken symlinks or locked files. Use deleteWhenDestroyed() in CLI tools, where process termination guarantees cleanup even if deletion fails.
  • Strict mode quirk: In older versions, strict mode (strict() was implied) caused leftover dirs on exceptions. Since v2.0+, the library avoids this — but always pair create() with either delete() or deleteWhenDestroyed().
  • Cross-platform path safety: The package uses PHP’s native sys_get_temp_dir(); avoid hardcoding /tmp or C:\Temp. Use $tempDir->path() for subpaths.
  • Non-recursive empty() caution: empty() uses FilesystemIterator — it deletes only direct contents. Subdirectories are not recursively removed (a common gotcha when building nested paths).
  • PHP version requirement: v2.x requires PHP 8+. For older PHP codebases, pin to ^1.3 — but be aware it lacks recent security and robustness fixes (e.g., strict mode, symlink fixes).
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport