Skip to content

Laravel File Upload: A Comprehensive Step-by-Step Tutorial

  • by
Laravel

Laravel File Upload

File uploading is an essential feature in many web applications, allowing users to upload various file types, such as images, documents, or videos. Laravel, a popular PHP framework, offers a smooth and secure way to handle file uploads. In this tutorial, we will explore how to set up and implement file uploads in Laravel from scratch. Whether you’re a beginner or an intermediate developer, this guide will help you master file uploading in Laravel.

1. Introduction to Laravel File Upload

File uploads are integral to modern web applications. Whether it’s uploading profile pictures, resumes, or multimedia content, having a reliable and secure file upload system is crucial. Laravel, with its built-in functions, makes this process straightforward and efficient. With support for file validation, storage, and security, Laravel offers a seamless way to manage file uploads.

In this tutorial, we will:

  • Create a file upload form.
  • Handle file validation.
  • Store files on the server.
  • Display the uploaded files.
  • Secure the file upload process.

By the end of this guide, you’ll have a solid understanding of how to implement and customize file uploads in Laravel applications.

2. Prerequisites

Before diving into the tutorial, ensure that the following are installed on your machine:

  • PHP >= 8.0
  • Composer (Dependency Manager for PHP)
  • Laravel 9 or higher
  • MySQL or SQLite for database management
  • Basic knowledge of Laravel and PHP

If you’re unfamiliar with how to set up Laravel, refer to the official Laravel documentation or use the following command to create a new Laravel project:

bash

Copy code

composer create-project –prefer-dist laravel/laravel file-upload-tutorial

 

Once the project is created, navigate to the project folder:

bash

Copy code

cd file-upload-tutorial

 

3. Setting Up a Laravel Project

Once your Laravel project is set up, let’s configure the basic settings:

Database Configuration: Open the .env file in the root directory and update your database credentials. If you’re using MySQL, update the following fields:
plaintext
Copy code
DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=laravel_upload

DB_USERNAME=root

DB_PASSWORD=

After configuring the .env file, run the following command to migrate the default tables:
bash
Copy code
php artisan migrate

A. Install Bootstrap (Optional)

To style the upload form, you can include Bootstrap for ease. In the resources/views/layouts folder, create a layout.blade.php file and include Bootstrap:

html
Copy code
<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>File Upload Tutorial</title>

    <link href=”https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css” rel=”stylesheet”>

</head>

<body>

    <div class=”container mt-5″>

        @yield(‘content’)

    </div>

</body>

</html>

4. Creating the File Upload Form

Now, let’s create a file upload form.

Create a Controller: Generate a controller for handling file uploads:
bash
Copy code
php artisan make:controller FileUploadController

Define the Form: In the resources/views folder, create a file called upload.blade.php with the following code:
html
Copy code
@extends(‘layouts.layout’)

 

@section(‘content’)

    <div class=”row”>

        <div class=”col-md-6 offset-md-3″>

            <h3 class=”text-center”>Upload a File</h3>

            <form action=”{{ route(‘file.upload.post’) }}” method=”POST” enctype=”multipart/form-data”>

                @csrf

                <div class=”form-group mb-3″>

                    <label for=”file”>Choose a file:</label>

                    <input type=”file” class=”form-control” name=”file” id=”file”>

                    @error(‘file’)

                        <small class=”text-danger”>{{ $message }}</small>

                    @enderror

                </div>

                <button type=”submit” class=”btn btn-primary”>Upload</button>

            </form>

        </div>

    </div>

@endsection

Set Up Routes: In the routes/web.php file, define the routes for displaying the form and handling file uploads:
php
Copy code
use App\Http\Controllers\FileUploadController;

 

Route::get(‘upload’, [FileUploadController::class, ‘showForm’])->name(‘file.upload’);

Route::post(‘upload’, [FileUploadController::class, ‘uploadFile’])->name(‘file.upload.post’);

5. Handling the File Upload Logic

In the FileUploadController.php, write the logic to handle the file upload process:

Show the Form:
php
Copy code
public function showForm() {

    return view(‘upload’);

}

Handle File Uploads:
In the same controller, add the following method to handle file uploads:
php
Copy code
public function uploadFile(Request $request) {

    // Validate the uploaded file

    $request->validate([

        ‘file’ => ‘required|file|mimes:jpeg,png,pdf,docx|max:2048’,

    ]);

 

    // Store the file

    if ($request->file(‘file’)) {

        $fileName = time() . ‘_’ . $request->file->getClientOriginalName();

        $filePath = $request->file(‘file’)->storeAs(‘uploads’, $fileName, ‘public’);

    }

 

    return back()->with(‘success’, ‘File uploaded successfully.’);

}

This method performs file validation, checks if the file is present, and stores it using the storeAs method.

6. Validating File Uploads

Validation is critical to ensure that users only upload allowed file types and sizes. Laravel’s validate method simplifies this process. The validation rules used here are:

  • required: Ensures the file is uploaded.
  • file: Ensures the uploaded item is a file.
  • mimes: Specifies allowed file types (e.g., jpeg, png, pdf, docx).
  • max: Specifies the maximum file size in kilobytes (e.g., 2048 KB = 2 MB).

You can customize these rules to fit your application’s requirements.

7. Storing Files

Laravel’s Storage facade allows you to store files easily. In the above example, we use the storeAs method to store the file in the public/uploads directory. To make the public/uploads folder accessible, you need to link the storage directory with the public folder. Run the following command:

bash

Copy code

php artisan storage:link

 

This command creates a symbolic link from storage/app/public to public/storage.

8. Displaying Uploaded Files

To display uploaded files, retrieve them from the storage folder and generate a URL using the Storage facade. Here’s how you can display images or files:

In the Controller:
php
Copy code
public function showUploads() {

    $files = Storage::disk(‘public’)->files(‘uploads’);

    return view(‘uploads’, compact(‘files’));

}

  1. In the View:

Create a resources/views/uploads.blade.php file:
html
Copy code
@extends(‘layouts.layout’)

 

@section(‘content’)

    <h3>Uploaded Files:</h3>

    <ul>

        @foreach($files as $file)

            <li><a href=”{{ asset(‘storage/’ . $file) }}”>{{ basename($file) }}</a></li>

        @endforeach

    </ul>

@endsection

  1. This will generate a list of uploaded files with download links.

9. Securing File Uploads

File uploads can pose security risks if not handled properly. Here are some best practices to secure file uploads:

  • Limit Allowed File Types: Always validate the file type using the mimes rule.
  • Limit File Size: Restrict file sizes to prevent excessive server resource consumption.
  • Use Proper File Naming: Store files using unique names to avoid overwriting existing files.
  • Scan Files: Consider using antivirus or file scanning tools to detect malicious uploads.
  • Restrict Public Access: Avoid storing sensitive files in publicly accessible directories. You can use Laravel’s storage directory for private files and create a controller to serve them securely.

10. Conclusion

File uploads are a vital feature for many web applications, and Laravel simplifies the process with its built-in tools and functionalities. In this tutorial, we’ve covered the basics of setting up file uploads, validating and storing files, displaying them, and securing the upload process. With this foundation, you can customize and extend the file upload functionality to suit your project’s needs.

Leave a Reply

Your email address will not be published. Required fields are marked *