Laravel

How to Handle File Uploads in Laravel

Administrator
By Administrator
Published Oct 07, 2025
4 min read
How to Handle File Uploads in Laravel

Introduction to File Uploads in Laravel

File uploads are a fundamental feature in most web applications. Laravel provides a robust and secure system for handling file uploads, including validation, storage, and file manipulation. In this guide, we'll explore how to handle various types of file uploads in Laravel applications.

Basic File Upload Form

Start by creating a form with proper file input fields. Remember to set the enctype attribute to "multipart/form-data":

@if(session('success'))
    
{{ session('success') }}
@endif @if(session('error'))
{{ session('error') }}
@endif
@csrf

File Upload Controller

Create a controller to handle file uploads:

php artisan make:controller UploadController

Now implement the upload logic:

// app/Http/Controllers/UploadController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{
    public function create()
    {
        return view('upload.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'file' => 'required|file|max:10240',
            'description' => 'nullable|string|max:255',
        ]);

        try {
            $path = $request->file('file')->store('uploads', 'public');

            $fileInfo = [
                'original_name' => $request->file('file')->getClientOriginalName(),
                'filename' => $request->file('file')->getClientOriginalExtension(),
                'mime_type' => $request->file('file')->getMimeType(),
                'size' => $request->file('file')->getSize(),
                'path' => $path,
                'description' => $request->description,
            ];

            return redirect()->route('upload.create')
                ->with('success', 'File uploaded successfully!');
        } catch (\Exception $e) {
            return redirect()->route('upload.create')
                ->with('error', 'File upload failed: ' . $e->getMessage());
        }
    }
}

Advanced File Validation

Laravel provides comprehensive file validation rules:

$request->validate([
    'avatar' => [
        'required',
        'file',
        'image',
        'max:2048',
        'mimes:jpeg,png,jpg,gif,svg',
        'dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000'
    ],
    'documents.*' => [
        'required',
        'file',
        'max:5120',
        'mimes:pdf,doc,docx,txt'
    ],
    'video' => [
        'nullable',
        'file',
        'max:51200',
        'mimes:mp4,mov,avi,wmv'
    ]
]);

Multiple File Uploads

To handle multiple file uploads, use the array syntax:

// Form with multiple file inputs
@csrf
// Controller method for multiple uploads public function storeMultiple(Request $request) { $request->validate([ 'files.*' => [ 'required', 'file', 'max:10240', 'mimes:jpg,jpeg,png,gif,pdf' ] ]); $paths = []; foreach ($request->file('files') as $file) { $paths[] = $file->store('uploads', 'public'); } return redirect()->route('upload.create') ->with('success', count($paths) . ' files uploaded successfully!'); }

Storage Configuration

Laravel provides flexible storage configuration. Define multiple storage disks in config/filesystems.php:

// config/filesystems.php
'disks' => [
    'local' => [
        'driver' => 'local',
        'root' => storage_path('app'),
    ],

    'public' => [
        'driver' => 'local',
        'root' => public_path('uploads'),
        'url' => env('APP_URL').'/uploads',
        'visibility' => 'public',
    ],

    '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'),
    ],

    'private' => [
        'driver' => 'local',
        'root' => storage_path('app/private'),
        'visibility' => 'private',
    ],
],

File Storage Methods

Use different storage methods based on your needs:

// Store in default disk
$path = $request->file('file')->store('uploads');

// Store in specific disk
$path = $request->file('file')->store('uploads', 'public');

// Store with custom filename
$filename = 'custom_name.'.$request->file('file')->getClientOriginalExtension();
$path = $request->file('file')->storeAs('uploads', $filename, 'public');

// Get file URL
$url = Storage::url($path);

// Move to permanent location
$request->file('file')->move(public_path('uploads'), $filename);

// Store with visibility
Storage::put('uploads/file.txt', 'content', 'public');

Database Integration

Create a model to store file information:

php artisan make:model UploadedFile -m

// database/migrations/xxxxxx_create_uploaded_files_table.php
Schema::create('uploaded_files', function (Blueprint $table) {
    $table->id();
    $table->string('original_name');
    $table->string('filename');
    $table->string('path');
    $table->string('disk');
    $table->string('mime_type');
    $table->integer('size')->unsigned();
    $table->text('description')->nullable();
    $table->timestamps();
});

// app/Models/UploadedFile.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class UploadedFile extends Model
{
    protected $fillable = [
        'original_name', 'filename', 'path', 'disk',
        'mime_type', 'size', 'description'
    ];

    public function getUrlAttribute()
    {
        return Storage::disk($this->disk)->url($this->path);
    }

    public function getHumanReadableSizeAttribute()
    {
        if ($this->size < 1024) {
            return $this->size . ' B';
        } elseif ($this->size < 1024 * 1024) {
            return round($this->size / 1024, 2) . ' KB';
        } else {
            return round($this->size / (1024 * 1024), 2) . ' MB';
        }
    }
}

File Download and Deletion

Handle file downloads and deletions securely:

// File download controller
public function download($id)
{
    $file = UploadedFile::findOrFail($id);

    return response()->download(
        Storage::disk($file->disk)->path($file->path),
        $file->original_name
    );
}

// File deletion controller
public function destroy($id)
{
    $file = UploadedFile::findOrFail($id);

    Storage::disk($file->disk)->delete($file->path);
    $file->delete();

    return redirect()->back()->with('success', 'File deleted successfully!');
}

Security Considerations

Always implement proper security measures for file uploads:

  • Validate file types and sizes to prevent malicious uploads
  • Use unique filenames to prevent overwrites
  • Scan files for malware if possible
  • Set proper file permissions (644 for files, 755 for directories)
  • Use content-type validation to prevent file extension exploits
  • Implement rate limiting to prevent abuse
  • Log uploads for security auditing

Conclusion

File handling in Laravel is straightforward yet powerful. By following these patterns, you can create secure, efficient file upload systems for your applications. Remember to always validate user input, implement proper security measures, and choose appropriate storage methods based on your application requirements.

Whether you're building a simple blog or a complex application, Laravel's file handling capabilities provide the tools you need to manage file uploads effectively.

Related Articles

Using Laravel Sanctum for API Authentication

Using Laravel Sanctum for API Authentication

Oct 07, 2025

Introduction to Laravel Sanctum Laravel Sanctum is a simple authentication library for SPAs (Sing...

How to Send Emails in Laravel Using Mailables

How to Send Emails in Laravel Using Mailables

Oct 07, 2025

Introduction to Laravel Mailables Sending emails in Laravel has never been easier thanks to Maila...

Laravel Queues and Jobs: Complete Beginner's Guide

Laravel Queues and Jobs: Complete Beginner's Guide

Oct 07, 2025

What Are Laravel Queues? Laravel Queues allow you to defer processing of time-consuming tasks. In...

Building RESTful APIs with Laravel

Building RESTful APIs with Laravel

Oct 07, 2025

Introduction to RESTful APIs in Laravel Building APIs is one of the most common tasks for modern...