📁 Day 1: File Uploads and Storage in Laravel

Week 19 - Mastering File Uploads, Storage Configuration, and Security

📚 Introduction to File Uploads in Laravel

Laravel provides a powerful and flexible file storage system built on top of Frank de Jonge's Flysystem PHP package. This abstraction allows you to seamlessly switch between local filesystem, Amazon S3, and other storage services with minimal code changes.

💡 Key Benefits:
  • Unified API for different storage systems
  • Built-in validation for file uploads
  • Automatic file naming and organization
  • Support for multiple storage disks
  • Security features for private file storage

⚙️ Storage Configuration (config/filesystems.php)

Laravel's storage system is configured in the config/filesystems.php file. This file defines various storage "disks" that your application can use.

Default Configuration

'default' => env('FILESYSTEM_DISK', 'local'), 'disks' => [ 'local' => [ 'driver' => 'local', 'root' => storage_path('app'), 'throw' => false, ], 'public' => [ 'driver' => 'local', 'root' => storage_path('app/public'), 'url' => env('APP_URL').'/storage', 'visibility' => 'public', 'throw' => false, ], 's3' => [ 'driver' => 's3', 'key' => env('AWS_ACCESS_KEY_ID'), 'secret' => env('AWS_SECRET_ACCESS_KEY'), 'region' => env('AWS_DEFAULT_REGION'), 'bucket' => env('AWS_BUCKET'), 'url' => env('AWS_URL'), 'endpoint' => env('AWS_ENDPOINT'), 'throw' => false, ], ],

Storage Disks Explained

Disk Description Use Case
local Private storage in storage/app Private documents, user data, temporary files
public Public storage in storage/app/public Profile pictures, product images, downloadable files
s3 Amazon S3 cloud storage Large-scale applications, CDN integration

✅ File Validation

Before storing uploaded files, it's crucial to validate them to ensure they meet your application's requirements and security standards.

Common Validation Rules

// In a Controller or Form Request public function store(Request $request) { $validated = $request->validate([ 'avatar' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', 'document' => 'required|file|mimes:pdf,doc,docx|max:5120', 'video' => 'nullable|mimetypes:video/avi,video/mpeg,video/mp4|max:51200', ]); // Process the validated files... }

Validation Rules Reference

Rule Description Example
file Must be a successfully uploaded file 'document' => 'file'
image Must be an image (jpeg, png, bmp, gif, svg, or webp) 'avatar' => 'image'
mimes File must have a MIME type from the list 'photo' => 'mimes:jpeg,png'
mimetypes File must match specified MIME types 'video' => 'mimetypes:video/mp4'
max Maximum file size in kilobytes 'file' => 'max:10240' (10MB)
min Minimum file size in kilobytes 'file' => 'min:100'
dimensions Image dimension constraints 'image' => 'dimensions:min_width=100,min_height=100'

Advanced Validation Example

use Illuminate\Validation\Rules\File; public function store(Request $request) { $validated = $request->validate([ 'avatar' => [ 'required', 'image', File::image() ->min(100) ->max(2 * 1024) ->dimensions(Rule::dimensions()->maxWidth(1000)->maxHeight(1000)), ], 'attachment' => [ 'required', File::types(['pdf', 'doc', 'docx']) ->max(10 * 1024), ], ]); }
⚠️ Security Warning: Never trust the file extension alone. Always validate MIME types and consider using additional security measures like antivirus scanning for user-uploaded files.

📤 Handling File Uploads

Laravel makes it easy to handle file uploads through the request object. Here are various methods to process uploaded files.

Basic File Upload Form

<!-- resources/views/upload.blade.php --> <form action="{{ route('files.store') }}" method="POST" enctype="multipart/form-data"> @csrf <div class="form-group"> <label for="avatar">Profile Picture</label> <input type="file" name="avatar" id="avatar" class="form-control" accept="image/*"> @error('avatar') <span class="text-danger">{{ $message }}</span> @enderror </div> <button type="submit" class="btn btn-primary">Upload</button> </form>

Controller - Basic Upload

namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; class FileUploadController extends Controller { public function store(Request $request) { // Validate the file $request->validate([ 'avatar' => 'required|image|mimes:jpeg,png,jpg|max:2048' ]); // Store the file if ($request->hasFile('avatar')) { $file = $request->file('avatar'); // Get file information $fileName = $file->getClientOriginalName(); $fileSize = $file->getSize(); $fileMimeType = $file->getMimeType(); // Store the file $path = $file->store('avatars', 'public'); return back()->with('success', 'File uploaded successfully!') ->with('path', $path); } return back()->with('error', 'No file uploaded.'); } }

💾 Storing Files Securely

Laravel provides multiple methods to store files with different levels of control and security.

Storage Methods

// 1. Store with automatic name generation $path = $request->file('avatar')->store('avatars'); // Result: avatars/random-hash.jpg // 2. Store on specific disk $path = $request->file('avatar')->store('avatars', 'public'); // Stores in storage/app/public/avatars // 3. Store with custom name $path = $request->file('avatar')->storeAs( 'avatars', auth()->id() . '-avatar.jpg', 'public' ); // Result: avatars/123-avatar.jpg // 4. Using Storage facade $path = Storage::disk('public')->put( 'avatars', $request->file('avatar') ); // 5. Store with custom name using Storage facade $path = Storage::disk('public')->putFileAs( 'avatars', $request->file('avatar'), 'custom-name.jpg' ); // 6. Get file contents and store $contents = file_get_contents($request->file('avatar')); Storage::disk('public')->put('avatars/file.jpg', $contents);

Complete Upload Example with User Model

namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; class ProfileController extends Controller { public function updateAvatar(Request $request) { $request->validate([ 'avatar' => 'required|image|mimes:jpeg,png,jpg|max:2048' ]); $user = auth()->user(); // Delete old avatar if exists if ($user->avatar) { Storage::disk('public')->delete($user->avatar); } // Generate unique filename $fileName = Str::slug($user->name) . '-' . time() . '.' . $request->file('avatar')->getClientOriginalExtension(); // Store new avatar $path = $request->file('avatar')->storeAs( 'avatars', $fileName, 'public' ); // Update user record $user->update([ 'avatar' => $path ]); return redirect()->back()->with('success', 'Avatar updated successfully!'); } }

🔍 Retrieving Files

Laravel provides various methods to retrieve and work with stored files.

File Retrieval Methods

use Illuminate\Support\Facades\Storage; // 1. Check if file exists if (Storage::disk('public')->exists('avatars/photo.jpg')) { // File exists } // 2. Get file contents $contents = Storage::disk('public')->get('avatars/photo.jpg'); // 3. Download a file return Storage::disk('public')->download('documents/report.pdf'); // 4. Download with custom name return Storage::disk('public')->download( 'documents/report.pdf', 'monthly-report.pdf' ); // 5. Get file URL (public disk only) $url = Storage::url('avatars/photo.jpg'); // Returns: /storage/avatars/photo.jpg // 6. Get temporary URL (for private files with S3) $url = Storage::temporaryUrl( 'documents/private.pdf', now()->addMinutes(5) ); // 7. Get file size $size = Storage::size('avatars/photo.jpg'); // 8. Get last modified time $time = Storage::lastModified('avatars/photo.jpg'); // 9. Get all files in directory $files = Storage::files('avatars'); // 10. Get all files recursively $files = Storage::allFiles('avatars');

Serving Private Files

namespace App\Http\Controllers; use Illuminate\Support\Facades\Storage; use Symfony\Component\HttpFoundation\StreamedResponse; class DocumentController extends Controller { public function show($id) { $document = Document::findOrFail($id); // Authorization check if (auth()->user()->cannot('view', $document)) { abort(403); } // Check if file exists if (!Storage::exists($document->path)) { abort(404); } // Return file response return response()->file(storage_path('app/' . $document->path)); } public function download($id) { $document = Document::findOrFail($id); // Authorization check $this->authorize('download', $document); return Storage::download( $document->path, $document->original_name ); } }

🖼️ Displaying Images

Learn how to properly display uploaded images in your Laravel application.

Creating the Symbolic Link

📌 Important: Before you can access files in the public disk via URL, you need to create a symbolic link from public/storage to storage/app/public.
# Run this Artisan command once php artisan storage:link # This creates: public/storage -> storage/app/public

Displaying Images in Blade Templates

<!-- Using Storage facade --> <img src="{{ Storage::url($user->avatar) }}" alt="User Avatar"> <!-- Using asset helper --> <img src="{{ asset('storage/' . $user->avatar) }}" alt="User Avatar"> <!-- With fallback image --> <img src="{{ $user->avatar ? Storage::url($user->avatar) : asset('images/default-avatar.png') }}" alt="User Avatar"> <!-- Responsive image with styling --> <div class="avatar-container"> <img src="{{ Storage::url($user->avatar) }}" alt="{{ $user->name }}" class="rounded-circle img-fluid" style="width: 150px; height: 150px; object-fit: cover;"> </div>

Creating Thumbnails (with Intervention Image)

// First install: composer require intervention/image use Intervention\Image\Facades\Image; public function store(Request $request) { $request->validate([ 'photo' => 'required|image|max:5120' ]); $file = $request->file('photo'); $fileName = time() . '-' . $file->getClientOriginalName(); // Store original $path = $file->storeAs('photos/originals', $fileName, 'public'); // Create thumbnail $thumbnail = Image::make($file) ->fit(300, 300) ->encode('jpg', 80); Storage::disk('public')->put( 'photos/thumbnails/' . $fileName, $thumbnail ); return back()->with('success', 'Photo uploaded with thumbnail!'); }

🔒 File Security

Implementing proper security measures for file uploads and storage is critical for protecting your application.

Public vs Private Storage

Storage Type Location Accessibility Use Cases
Public storage/app/public Direct URL access via /storage Profile pictures, product images, public documents
Private storage/app Only via controller with authentication User documents, invoices, sensitive files

Secure File Upload Implementation

namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; class SecureFileController extends Controller { public function __construct() { $this->middleware('auth'); } public function store(Request $request) { $request->validate([ 'document' => [ 'required', 'file', 'mimes:pdf,doc,docx', 'max:10240', // 10MB ] ]); $file = $request->file('document'); // Generate secure random filename $fileName = Str::random(40) . '.' . $file->getClientOriginalExtension(); // Store in private storage $path = $file->storeAs( 'documents/' . auth()->id(), $fileName, 'local' // Private disk ); // Save metadata to database auth()->user()->documents()->create([ 'original_name' => $file->getClientOriginalName(), 'file_path' => $path, 'file_size' => $file->getSize(), 'mime_type' => $file->getMimeType(), ]); return back()->with('success', 'Document uploaded securely!'); } public function show($id) { $document = auth()->user()->documents()->findOrFail($id); if (!Storage::exists($document->file_path)) { abort(404, 'File not found'); } return response()->file( storage_path('app/' . $document->file_path) ); } public function destroy($id) { $document = auth()->user()->documents()->findOrFail($id); // Delete file from storage Storage::delete($document->file_path); // Delete database record $document->delete(); return back()->with('success', 'Document deleted successfully!'); } }

Additional Security Best Practices

🛡️ Security Checklist:
  • Validate MIME types: Don't rely on file extensions alone
  • Limit file sizes: Prevent denial-of-service attacks
  • Sanitize filenames: Use random names or sanitize user input
  • Store sensitive files privately: Use local disk, not public
  • Implement authorization: Check user permissions before serving files
  • Scan for malware: Consider integrating antivirus scanning
  • Use HTTPS: Encrypt file transfers
  • Set proper permissions: Ensure storage directories have correct permissions

🔗 Symbolic Links

Understanding and managing symbolic links for public file access.

What is a Symbolic Link?

A symbolic link is a special type of file that points to another file or directory. In Laravel, we use it to make the storage/app/public directory accessible from the web by creating a link in the public directory.

Creating the Storage Link

# Command line method php artisan storage:link # Output: # The [public/storage] link has been connected to [storage/app/public]. # Verify the link was created ls -la public/storage # On Unix/Linux/Mac dir public\storage # On Windows

Custom Symbolic Links

// In config/filesystems.php 'links' => [ public_path('storage') => storage_path('app/public'), public_path('images') => storage_path('app/images'), public_path('documents') => storage_path('app/documents'), ], // After adding custom links, run: // php artisan storage:link

Troubleshooting Symbolic Links

// If link already exists # Delete the old link first rm public/storage # Unix/Linux/Mac rmdir public\storage # Windows # Then recreate php artisan storage:link // On shared hosting without shell access // Create a route to manually create the link Route::get('/create-storage-link', function () { if (!file_exists(public_path('storage'))) { symlink(storage_path('app/public'), public_path('storage')); return 'Storage link created successfully!'; } return 'Storage link already exists!'; });

📚 Multiple File Uploads

Handle uploading multiple files simultaneously with proper validation and storage.

Multiple Upload Form

<!-- resources/views/gallery/create.blade.php --> <form action="{{ route('gallery.store') }}" method="POST" enctype="multipart/form-data"> @csrf <div class="form-group"> <label for="images">Upload Photos (Multiple)</label> <input type="file" name="images[]" id="images" class="form-control" multiple accept="image/*"> @error('images.*') <span class="text-danger">{{ $message }}</span> @enderror </div> <div class="form-group"> <label for="title">Gallery Title</label> <input type="text" name="title" id="title" class="form-control"> </div> <button type="submit" class="btn btn-primary">Upload Gallery</button> </form> <!-- Preview uploaded images with JavaScript --> <div id="preview" class="row mt-3"></div> <script> document.getElementById('images').addEventListener('change', function(e) { const preview = document.getElementById('preview'); preview.innerHTML = ''; Array.from(e.target.files).forEach(file => { const reader = new FileReader(); reader.onload = function(e) { const col = document.createElement('div'); col.className = 'col-md-3 mb-3'; col.innerHTML = `<img src="${e.target.result}" class="img-fluid img-thumbnail">`; preview.appendChild(col); } reader.readAsDataURL(file); }); }); </script>

Controller - Multiple Files

namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use App\Models\Gallery; class GalleryController extends Controller { public function store(Request $request) { $request->validate([ 'title' => 'required|string|max:255', 'images' => 'required|array|min:1|max:10', 'images.*' => 'required|image|mimes:jpeg,png,jpg|max:2048' ]); // Create gallery $gallery = Gallery::create([ 'title' => $request->title, 'user_id' => auth()->id(), ]); // Process each image $uploadedImages = []; foreach ($request->file('images') as $image) { // Generate unique filename $fileName = time() . '-' . uniqid() . '.' . $image->getClientOriginalExtension(); // Store image $path = $image->storeAs('galleries/' . $gallery->id, $fileName, 'public'); // Save to database $gallery->images()->create([ 'path' => $path, 'filename' => $fileName, 'size' => $image->getSize(), ]); $uploadedImages[] = $path; } return redirect() ->route('gallery.show', $gallery) ->with('success', count($uploadedImages) . ' images uploaded successfully!'); } public function show(Gallery $gallery) { return view('gallery.show', compact('gallery')); } }

Database Migration for Gallery

// database/migrations/xxxx_create_galleries_table.php public function up() { Schema::create('galleries', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->string('title'); $table->timestamps(); }); Schema::create('gallery_images', function (Blueprint $table) { $table->id(); $table->foreignId('gallery_id')->constrained()->onDelete('cascade'); $table->string('path'); $table->string('filename'); $table->integer('size'); $table->timestamps(); }); }

Display Gallery

<!-- resources/views/gallery/show.blade.php --> @extends('layouts.app') @section('content') <div class="container"> <h1>{{ $gallery->title }}</h1> <div class="row"> @foreach($gallery->images as $image) <div class="col-md-3 mb-4"> <div class="card"> <img src="{{ Storage::url($image->path) }}" class="card-img-top" alt="Gallery Image" style="height: 200px; object-fit: cover;"> <div class="card-body"> <p class="card-text"> Size: {{ number_format($image->size / 1024, 2) }} KB </p> <form action="{{ route('gallery.image.destroy', $image) }}" method="POST"> @csrf @method('DELETE') <button type="submit" class="btn btn-danger btn-sm">Delete</button> </form> </div> </div> </div> @endforeach </div> </div> @endsection

🎯 Practical Exercises

Exercise 1: Profile Avatar Upload

Objective: Create a profile avatar upload system with validation and preview.

Requirements:

  • Create a form to upload profile avatars
  • Validate: image type, max 2MB, dimensions at least 200x200
  • Store in public storage with user-specific naming
  • Delete old avatar when uploading new one
  • Display avatar on profile page with fallback
  • Add JavaScript preview before upload

Bonus: Create both original and thumbnail versions

Exercise 2: Document Management System

Objective: Build a secure document upload and management system.

Requirements:

  • Allow users to upload PDF, DOC, DOCX files (max 10MB)
  • Store files in private storage
  • Create a documents table with: original_name, file_path, file_size, mime_type
  • Display list of user's documents with download links
  • Implement authorization (users can only access their own files)
  • Add ability to delete documents
  • Show file size in human-readable format

Bonus: Add file search and filtering functionality

Exercise 3: Photo Gallery with Multiple Uploads

Objective: Create a photo gallery system supporting multiple image uploads.

Requirements:

  • Form to upload multiple images at once (3-10 images)
  • Validate each image: jpeg/png, max 5MB per image
  • Create gallery and gallery_images tables
  • Store images in public storage organized by gallery ID
  • Display gallery with grid layout
  • Add ability to delete individual images
  • Show upload progress for multiple files

Bonus: Add image reordering and gallery cover selection

Exercise 4: File Type Icons

Objective: Display appropriate icons for different file types.

Requirements:

  • Create a helper function to determine file type from MIME type
  • Display different icons for: PDF, Word, Excel, Images, Videos, Others
  • Create a file listing page showing: icon, filename, size, upload date
  • Add download functionality for each file
  • Show file count by type

Bonus: Add inline preview for images and PDFs

Exercise 5: Advanced File Management

Objective: Build a complete file management system with folders.

Requirements:

  • Allow users to create folders
  • Upload files to specific folders
  • Move files between folders
  • Rename files and folders
  • Display breadcrumb navigation
  • Show total storage used by user
  • Implement file sharing with other users

Bonus: Add zip download for folders and search functionality

📦 Deliverable

Project: Personal Document Manager

Create a complete personal document management application with the following features:

Core Features:

  1. User Authentication:
    • User registration and login
    • Profile page with avatar upload
  2. Document Upload:
    • Single and multiple file upload
    • Support for PDF, DOC, DOCX, images (jpg, png)
    • File validation (type and size)
    • Upload progress indication
  3. Document Organization:
    • Create folders/categories
    • Move documents between folders
    • Rename documents and folders
    • Tag documents with custom labels
  4. Document Viewing:
    • List view with file icons
    • Grid view for images
    • Search and filter documents
    • Sort by name, date, size
  5. Security:
    • Private file storage
    • User-level access control
    • Secure file serving through controller
    • File download with original name
  6. Storage Management:
    • Display total storage used
    • Show storage breakdown by file type
    • Delete files to free up space
    • Storage limit per user (optional)

Database Schema:

users: id, name, email, password, avatar, storage_limit folders: id, user_id, name, parent_id (for nested folders) documents: id, user_id, folder_id, original_name, stored_name, file_path, file_size, mime_type, timestamps tags: id, user_id, name document_tag: document_id, tag_id

Technical Requirements:

  • Use Laravel's file validation rules
  • Store sensitive documents in private storage (local disk)
  • Store profile pictures in public storage
  • Create symbolic link for public storage
  • Implement proper authorization policies
  • Use Bootstrap for responsive UI
  • Add success/error flash messages
  • Include JavaScript for file preview

Bonus Features:

  • Generate thumbnails for images
  • PDF preview in browser
  • Share documents with other users
  • Export folder as ZIP
  • Activity log for file operations
  • File versioning system

Submission Requirements:

  1. Complete Laravel application code
  2. Database migrations and seeders
  3. README with setup instructions
  4. Screenshots showing all features
  5. Video demonstration (2-3 minutes)

✅ Key Takeaways

  • Laravel provides a unified API for file storage across different systems
  • Always validate file uploads (type, size, dimensions)
  • Use public storage for accessible files, private storage for sensitive files
  • Create symbolic links to access public storage files via URL
  • Generate unique filenames to prevent conflicts and improve security
  • Implement proper authorization when serving private files
  • Delete old files when uploading replacements to save storage
  • Use the Storage facade for consistent file operations
  • Handle multiple file uploads with array validation
  • Store file metadata in database for better management