Laravel 9 File Upload with Validation Example Tutorial

Published On: 09/06/2022 | Category: Laravel Laravel 9

Hi Dev,

This tutorial will provide example of Laravel 9 File Upload with Validation Example Tutorial. you can see Laravel 9 File Upload Tutorial. you can understand a concept of How to Upload File in Laravel 9 With Validation?. I explained simply step by step Laravel 9 File Upload Step by Step Example. follow bellow step for Laravel 9 File Upload Tutorial: Validation + Store in Database.

This article will give you simple example of Laravel 9 File Upload Validation Example Tutorial

Let's start following example:

Step 1: Install Laravel

First of all we are going from scratch new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app
Step 2 : Create New Migration

create migration table using Laravel 9 php artisan command, so first fire bellow command:

php artisan make:migration create_files_table
database/migrations/create_files_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('files', function (Blueprint $table) {
            $table->id();
            $table->string('file');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('files');
    }
};

now, we need to run migration command to create database table:

php artisan migrate
Step 3 : Create New Model

Here, we already have table created, so we need create model run command to create model:

php artisan make:model File
app/Models/File.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    use HasFactory;

    protected $fillable = [
        'file',
    ];
}
Step 4 : Create New Controller

In this second step, we need to create a new FileUploadController; in this file, we will add two method index() and store() for render view and store image logic.

Let's create FileUploadController by following command:

php artisan make:controller FileUploadController
app/Http/Controllers/FileUploadController.php
<?php

namespace App\Http\Controllers;

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

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

    public function store(Request $request)
    {
        $request->validate(
        [
            'file' => 'required|mimes:pdf,csv,txt,xlx,xls|max:2048',
        ]);
        
        $name = $request->file('file')->getClientOriginalName();
 
        $request->file->move(public_path('files'), $name);
 
        $fileName = new File;
 
        $fileName->file = $name;
        $fileName->save();
 
        return redirect()->back()->with('success','You have successfully upload File.');
 
    }
}
Step 5 : Create Routes routes/web.php
<?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('/file',[FileUploadController::class, 'index']);
Route::post('upload-file',[FileUploadController::class, 'store'])->name('file.store');
Step 6: Create Blade File resources/views/index.blade.php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel 9 File Upload with Validation Example Tutorial</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-primary">
                        <h5 class="text-center text-white">Laravel 9 File Upload with Validation Example Tutorial - Tuts-Station.com</h5>
                    </div>
                    <div class="card-body">
                        @if(session('success'))
                            <div class="alert alert-success alert-dismissible fade show successAlert" role="alert">
                                {{ session('success') }}
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                        @endif
                        <form action="{{ route('file.store') }}" method="POST" enctype="multipart/form-data">
                            @csrf
                            <div class="mt-2">
                                <label>Select File : <span class="text-danger">*</span></label>
                                <input type="file" name="file" class="form-control @error('file') is-invalid @enderror">
                                @error('file')
                                    <span class="text-danger">{{ $message }}</span>
                                @enderror
                            </div>
                            <div class="text-center mt-3">
                                <button type="submit" class="btn btn-primary">Submit</button>
                            </div>
                            </div>     
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
Run Laravel App:

All steps have been done, now you have to type the given command and hit enter to run the laravel app:

php artisan serve
Output :

I hope it can help you...