Laravel 11 File Upload With Validation

Laravel 11 file upload; Through this tutorial, i am going to show you how to upload file in Laravel 11 apps with validation into database and public storage directory (folder).

Laravel 11 File Upload With Validation

Use below given steps to upload file in Laravel 11 apps:

  • Step 1 – Install Laravel 11 Application
  • Step 2 – Configuring Database Details
  • Step 3 – Create File Model & Migration
  • Step 4 – Create File Upload Routes
  • Step 5 – Creating File Upload Controller
  • Step 6 – Create File Upload Blade View
  • Step 7 – Start Development Server
  • Step 8 – Run Laravel 11 File Upload with Validation App On Browser

Step 1 – Install Laravel 11 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install Laravel 11 latest application using the following command:

composer create-project --prefer-dist laravel/laravel LaravelFileUpload

Step 2 – Configuring Database Details

In step 2, open your downloaded laravel app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Create File Model & Migration

In step 3, open command prompt and navigate to your project by using the following command:

cd / LaravelFileUpload

Then create model and migration file by using the following command:

php artisan make:model File -m

The above command will create two files into your laravel file upload tutorial app, which is located inside the following locations:

  • LaravelFileUpload/app/Models/File.php
  • LaravelFileUpload/database/migrations/create_files_table.php

So, find create_files_table.php file inside LaravelFileUpload/database/migrations/ directory. Then open this file and add the following code into function up() on this file:

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

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 4 – Create File Upload Routes

In step 4, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileUploadController;


/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});


Route::get('file-upload', [FileUploadController::class, 'index']);
Route::post('file-store', [FileUploadController::class, 'storeFile']);

Step 5 – Creating File Upload Controller

In step 5, create file upload controller by using the following command:

php artisan make:controller FileUploadController

The above command will create FileUploadController.php file, which is located inside LaravelFileUpload/app/Http/Controllers/ directory.

The following laravel validation rules will validate file before upload/save into database:

        $validatedData = $request->validate([
          'file' => 'required|mimes:csv,txt,xlx,xls,pdf|max:2048'
        ]);

So open FileController.php file and add the following code into it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\File;

class FileUploadController extends Controller
{
     public function index()
    {
        return view('file-upload');
    }

    public function storeFile(Request $request)
    {
        
        $validatedData = $request->validate([
          'file' => 'required|mimes:csv,txt,xlx,xls,pdf|max:2048'
        ]);

        $name = $request->file('file')->getClientOriginalName();

        $path = $request->file('file')->store('public/files');


        $save = new File;

        $save->name = $name;
        $save->path = $path;

        $save->save();

        return redirect('file-upload')->with('status', 'File Has been uploaded');

    }
}

The following single line of code will upload files inside storage/app/public/files directory:

        $path = $request->file('file')->store('public/files');

Step 6 – Create File Upload Blade View

In step 6, create new blade view file that named file-upload.php inside resources/views directory for file upload form.

The following code display error message in laravel file upload forms. So do not forget to add the following code along laravel forms fields:

          @error('file')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror

Don’t worry i have already added the validation error message display code along with form fields.

So, you can add the following php and html form code into file-upload.blade.php:

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 11 File Upload Tutorial</title>

  <meta name="csrf-token" content="{{ csrf_token() }}">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

</head>
<body>

<div class="container mt-4">

  <div class="card">

    <div class="card-header text-center font-weight-bold">
      <h2>Laravel 11 File Upload Tutorial</h2>
    </div>

    <div class="card-body">
        <form method="POST" enctype="multipart/form-data" id="file-upload" action="{{ url('file-store') }}" >
                  
            <div class="row">

                <div class="col-md-12">
                    <div class="form-group">
                        <input type="file" name="file" placeholder="Choose file " id="file">
          @error('file')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror
                    </div>
                </div>
                  
                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary" id="submit">Submit</button>
                </div>
            </div>     
        </form>

    </div>

  </div>

</div>  
</body>
</html>

Step 7 – Start Development Server

Finally, open your command prompt again and run the following command to start development server for your laravel file upload application:

php artisan serve

Step 8 – Run Laravel 11 File Upload with Validation App On Browser

In step 8, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/file-upload

Note that, in this example, the file will be upload on the following path – storage/app/public/files.

Recommended Laravel Tutorials

Leave a Comment