Mastering File Uploads in Laravel 10 Validation and Database Storage

Spread the love

Laravel 10: Managing file uploads is a regular task for site developers in today’s digital age. Whether you’re creating a content management system, an e-commerce platform, or any other web application that deals with user-generated content, you’ll almost certainly need to include secure and quick file upload capability. Laravel 10, the most recent version of this renowned PHP framework, includes sophisticated capabilities to make this task easier. We’ll walk you through the steps of creating a powerful file upload system in Laravel 10 in this comprehensive article. We’ll go over everything from project setup to validation and database storage, among other things.

1. Introduction

Handling file uploads in web applications is a basic necessity in this digital age. Laravel 10, the most recent version of the well-known PHP framework, provides an easy approach to manage file uploads while maintaining security and data integrity. In this tutorial, you will learn how to use Laravel 10 to create a file upload system with validation and database storage.

2. Installation of a Laravel 10 Project

Before we get started with file uploads, let’s create a Laravel 10 project. To create a new Laravel project, use the following line, assuming you have Composer installed:

composer create-project laravel/laravel my-file-upload-app

When the installation is finished, go to your project folder:

cd my-file-upload-app

3. Creating and Configuring Routes

Routes in Laravel define the entrance points to your application. We’ll need a route that points to a controller method to handle file uploads. Let’s make a new path:

// routes/web.php
Route::get('/upload', 'UploadController@index');
Route::post('/upload', 'UploadController@store');

Create the controller be running the following command :

php artisan make:controller UploadController

4. Building a Blade File

A Blade view will be created to give a user interface for file uploads. Create a new Blade view file first:

php artisan make:view upload

Then, under the 'resources/views' folder, open the produced 'upload.blade.php' file and add the HTML form for file uploads.

<!-- resources/views/upload.blade.php -->
<form method="POST" action="/upload" enctype="multipart/form-data">
    @csrf
    <input type="file" name="file">
    <button type="submit">Upload</button>
</form>

5. Setting up Database Migration in Laravel 10

A database table will be created to store information about uploaded files. This is made easier by Laravel’s migrations. To make a migration for our files table, run the following command:

php artisan make:migration create_files_table

Open the created migration file and specify the table schema as follows:

// database/migrations/xxxx_xx_xx_create_files_table.php
public function up()
{
    Schema::create('files', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('path');
        $table->timestamps();
    });
}

To create the 'files' table, run the migration:

php artisan migrate

6. Create the Model to store file in database

We construct a new 'File' model and change our 'UploadController' to use it to correlate file uploads with database storage. Create the model first:

php artisan make:model File

Open the 'File.php' model and define the table name and fillable fields as follows:

// app/Models/File.php
class File extends Model
{
    protected $table = 'files';

    protected $fillable = ['name', 'path'];
}

Import the 'File' model into our 'UploadController' and use it to store file information:

// app/Http/Controllers/UploadController.php
use App\Models\File;

7. Implementing Basic Validation for File Uploads

It is critical to evaluate file uploads before accepting them to ensure they satisfy your standards. Laravel makes this procedure easier. Add the following validation rules to the 'store' method in our ‘UploadController’:

// app/Http/Controllers/UploadController.php
public function store(Request $request)
{
    $request->validate([
        'file' => 'required|file|mimes:csv,txt,xlsx,xls,pdf|max:2048', // 2MB limit
    ]);

    // Handle file upload and database storage here
}

8. Displaying Status Messages for File Uploads

It is critical to provide consumers with feedback on the upload process. To display messages, we can use Laravel’s session flash. Add the following code to our 'UploadController's' 'store' method to display success or error messages:

// app/Http/Controllers/UploadController.php
public function store(Request $request)
{
    $request->validate([
        'file' => 'required|file|mimes:csv,txt,xlsx,xls,pdf|max:2048', // 2MB limit
    ]);

    // Handle file upload and database storage here

    return redirect('/upload')->with('success', 'File uploaded successfully!');
}

Display the following flash message in your 'upload.blade.php' view:

<!-- resources/views/upload.blade.php -->
@if(session('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif

9. Allowing Only Specific File Types with Database Storage

Let’s finish the 'store' method in our 'UploadController' to handle file uploads and save them in the database:

// app/Http/Controllers/UploadController.php
use Illuminate\Support\Facades\Storage;

public function store(Request $request)
{
    $request->validate([
        'file' => 'required|file|mimes:csv,txt,xlsx,xls,pdf|max:2048', // 2MB limit
    ]);

    // Handle file upload and database storage
    if ($request->hasFile('file')) {
        $file = $request->file('file');
        $path = $file->store('uploads');
        
        // Store file information in the database
        File::create([
            'name' => $file->getClientOriginalName(),
            'path' => $path,
        ]);

        return redirect('/upload')->with('success', 'File uploaded successfully!');
    }
}

Conclusion

In this tutorial, we looked at how to use Laravel 10 to construct secure and efficient file uploads with validation and database storage. We began by building a Laravel project, configuring routes, and a Blade file for file uploads. We next implemented file validation, displayed status messages, and restricted file types to those with a maximum size restriction. Finally, we used Laravel’s migration and model to store uploaded files in the database.

You’ve learned a lot about creating a solid file upload system in Laravel 10 by following these instructions. This expertise will enable you to handle user-generated material in your web apps in a simple and secure manner. Feel free to investigate more and modify these strategies to match your needs.

Some times we need to create a simple admin panel for our app. I’ve created a article Simplifying Admin Panel Creation in Laravel 10 Using Middleware where I discussed about creating a middleware to manage a simple admin panel in details.

Also if you are looking for a Client from where we can upload files or images using this API, I’ve written an article “Elevate Your Vue 3 App Image Upload with Preview and API Integration” where I’ve explained in details how to upload a file using Vue 3.