Navigation

Laravel

How to Store an Uploaded File to a Specific Disk

Save uploaded files to different storage locations in Laravel using disks. Configure local, public, or cloud storage for file uploads.

Problem: You need to store uploaded files in specific locations like public folders, private storage, or cloud services like S3, but aren't sure how to specify the destination.

Solution:

// Store to default disk
public function upload(Request $request)
{
    $request->validate([
        'document' => 'required|file|mimes:pdf,doc,docx|max:10240'
    ]);
    
    // Store to default disk (usually 'local')
    $path = $request->file('document')->store('documents');
    
    // Store to specific disk
    $path = $request->file('document')->store('documents', 'public');
    $path = $request->file('document')->storeAs('documents', 'custom-name.pdf', 's3');
    
    // Store with custom filename
    $file = $request->file('document');
    $filename = time() . '_' . $file->getClientOriginalName();
    $path = $file->storeAs('documents', $filename, 'public');
    
    return ['path' => $path, 'url' => Storage::disk('public')->url($path)];
}

// Using Storage facade
use Illuminate\Support\Facades\Storage;

public function uploadAdvanced(Request $request)
{
    $file = $request->file('avatar');
    
    // Store to different disks
    Storage::disk('public')->put('avatars/' . $file->hashName(), $file);
    Storage::disk('s3')->put('avatars/' . $file->hashName(), $file);
    
    // Store with visibility
    $path = Storage::disk('s3')->putFile('avatars', $file, 'public');
    
    // Store multiple files
    foreach ($request->file('photos') as $photo) {
        $paths[] = $photo->store('photos/' . auth()->id(), 'public');
    }
}

// Configure disks in config/filesystems.php
'disks' => [
    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],
    
    'private' => [
        'driver' => 'local',
        'root' => storage_path('app/private'),
    ],
    
    'temp' => [
        'driver' => 'local',
        'root' => storage_path('app/temp'),
    ],
],

// Create symbolic link for public disk
php artisan storage:link

Why it works: Laravel's filesystem abstraction lets you switch between local and cloud storage without changing code. The store() method generates unique filenames automatically, while storeAs() lets you specify names. Each disk has its own configuration for root path and visibility.

Important: Files stored in public disk are web-accessible after running storage:link. Use local or custom private disks for sensitive files.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Laravel