advanced Step 13 of 15

File Storage

Laravel Framework

File Storage

Laravel's filesystem abstraction provides a clean API for working with local files, Amazon S3, and other cloud storage providers through a unified interface. The Storage facade lets you read, write, move, and delete files without worrying about the underlying storage driver. This abstraction means you can develop locally with the local disk and deploy to S3 in production just by changing a configuration value, without modifying any application code.

File Upload and Storage

<?php
use Illuminate\Support\Facades\Storage;

// Handle file upload in controller
public function uploadAvatar(Request $request)
{
    $request->validate([
        'avatar' => 'required|image|max:2048|mimes:jpg,png,webp',
    ]);

    // Store the file and get the path
    $path = $request->file('avatar')->store('avatars', 'public');
    // Returns: "avatars/random-hash.jpg"

    // Store with a custom filename
    $path = $request->file('avatar')->storeAs(
        'avatars',
        auth()->id() . '.' . $request->file('avatar')->extension(),
        'public'
    );

    // Update user record
    auth()->user()->update(['avatar_path' => $path]);

    return back()->with('success', 'Avatar uploaded!');
}

// Working with Storage facade
Storage::disk('public')->put('file.txt', 'Contents here');
$contents = Storage::disk('public')->get('file.txt');
$exists = Storage::disk('public')->exists('file.txt');
Storage::disk('public')->delete('old-file.txt');

// Get public URL
$url = Storage::disk('public')->url($path);
// Requires: php artisan storage:link

// List files in a directory
$files = Storage::disk('public')->files('avatars');
$allFiles = Storage::disk('public')->allFiles('uploads');

// Download file
return Storage::download('reports/monthly.pdf', 'report.pdf');
Pro tip: Run php artisan storage:link to create a symbolic link from public/storage to storage/app/public, making stored files accessible via the web. For production, switch to S3 by changing FILESYSTEM_DISK=s3 in your .env file — no code changes needed.

Key Takeaways

  • Laravel's Storage facade provides a unified API for local, S3, and other storage drivers.
  • Use $request->file('name')->store('directory') for simple file uploads.
  • Run php artisan storage:link to make public disk files accessible via URLs.
  • Switch between local and cloud storage by changing the FILESYSTEM_DISK environment variable.
  • Always validate file type, size, and MIME type before storing uploaded files.