---
description: https://www.positronx.io/laravel-file-upload-with-validation/
---

# 👏 File Upload: Validation, Store in Database, Storage link, Tạo lệnh php artisan bằng route(Phần 1)

### Lệnh php artisan vendor:publish mới sử dụng tác dụng publish phần vendor

```
 php artisan vendor:publish
```

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FwFS8b1PdVw5SHSa4Q0S4%2Fimage.png?alt=media&#x26;token=4381c624-67c9-42ea-8f7f-9beb74cb3477" alt=""><figcaption></figcaption></figure>

### Bước 1: Upload file vào thư  mục storage/uploads

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2Fyr3RnoDYVBhIcvyzWslh%2Fimage.png?alt=media&#x26;token=4f4f1ce8-044d-469f-817a-ec1f27ec3d78" alt=""><figcaption></figcaption></figure>

C:\xampp8\htdocs\plugindev\database\migrations\2022\_12\_29\_091725\_create\_files\_table.php

```php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFilesTable extends Migration
{
  public function up()
  {
    Schema::create('files', function (Blueprint $table) {
      $table->id();
      $table->string('name')->nullable();
      $table->string('file_path')->nullable();
      $table->timestamps();
    });
  }
  public function down()
  {
    Schema::dropIfExists('files');
  }
}

```

C:\xampp8\htdocs\plugindev\app\Models\File.php

```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
  use HasFactory;
  protected $fillable = [
    'name',
    'file_path'
  ];
}

```

C:\xampp8\htdocs\plugindev\resources\views\file-upload.blade.php

```
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <title>Laravel File Upload</title>
  <style>
    .container {
      max-width: 500px;
    }
    dl,
    ol,
    ul {
      margin: 0;
      padding: 0;
      list-style: none;
    }
  </style>
</head>
<body>
  <div class="container mt-5">
    <form action="{{route('fileUpload')}}" method="post" enctype="multipart/form-data">
      <h3 class="text-center mb-5">Upload File in Laravel</h3>
      @csrf
      @if ($message = Session::get('success'))
      <div class="alert alert-success">
        <strong>{{ $message }}</strong>
      </div>
      @endif
      @if (count($errors) > 0)
      <div class="alert alert-danger">
        <ul>
          @foreach ($errors->all() as $error)
          <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif
      <div class="custom-file">
        <input type="file" name="file" class="custom-file-input" id="chooseFile">
        <label class="custom-file-label" for="chooseFile">Select file</label>
      </div>
      <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
        Upload Files
      </button>
    </form>
  </div>
</body>
</html>

```

C:\xampp8\htdocs\plugindev\routes\web.php

```php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileUpload;
/*
|--------------------------------------------------------------------------
| 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('/upload-file', [FileUpload::class, 'createForm']);
Route::post('/upload-file', [FileUpload::class, 'fileUpload'])->name('fileUpload');
Route::get('/use-file', [FileUpload::class, 'use_file']);
```

C:\xampp8\htdocs\plugindev\app\Http\Controllers\FileUpload.php

```php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\File;
class FileUpload extends Controller
{
  public function createForm()
  {
    return view('file-upload');
  }
  public function fileUpload(Request $req)
  {
    $req->validate([
      'file' => 'required|mimes:csv,txt,xlx,xls,pdf,jpg,png|max:20048'
    ]);
    $fileModel = new File;
    if ($req->file()) {
      $fileName = time() . '_' . $req->file->getClientOriginalName();
      $filePath = $req->file('file')->storeAs('uploads', $fileName, 'public');
      $fileModel->name = time() . '_' . $req->file->getClientOriginalName();
      $fileModel->file_path = '/storage/' . $filePath;
      $fileModel->save();
      return back()
        ->with('success', 'File has been uploaded.')
        ->with('file', $fileName);
    }
  }
  public function use_file()
  {
    $files = File::all();
    return view('use-file')->with(compact('files'));
  }
}
```

C:\xampp8\htdocs\plugindev\database\migrations\2022\_12\_29\_091725\_create\_files\_table.php

```php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFilesTable extends Migration
{
  public function up()
  {
    Schema::create('files', function (Blueprint $table) {
      $table->id();
      $table->string('name')->nullable();
      $table->string('file_path')->nullable();
      $table->timestamps();
    });
  }
  public function down()
  {
    Schema::dropIfExists('files');
  }
}
```

Kết quả sau khi upload file trên database như này :)

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FYrcRby8hkOhevq0jPvAx%2Fimage.png?alt=media&#x26;token=54d63b72-d072-4c3e-bc08-041b972cd197" alt=""><figcaption></figcaption></figure>

### Bước 2: Tạo [Storage link](https://stackoverflow.com/questions/50185273/laravel-5-4-storage-link) [storage symbolic link for production or sub domain](https://stackoverflow.com/questions/45825889/how-to-create-laravel-storage-symbolic-link-for-production-or-sub-domain-system)

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2F84SpdxAjXg0SMLwuYsq3%2Fimage.png?alt=media&#x26;token=5c7af7e7-2fc5-4f30-bdd1-28b838fd83d8" alt=""><figcaption></figcaption></figure>

Thật tuyệt vời giờ trong  C:\xampp8\htdocs\plugindev\public\storage\uploads nó cũng chứa các file  giống với&#x20;

```
php artisan storage:link
```

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FXUmkBn8e9R2suJuYCujN%2Fimage.png?alt=media&#x26;token=367982a8-2386-4049-abd1-389061f761eb" alt=""><figcaption></figcaption></figure>

C:\xampp8\htdocs\plugindev\storage\app\public\uploads

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FFyZ5uYRDYN5M36ZuCJRW%2Fimage.png?alt=media&#x26;token=e12fc4d4-e478-4e06-b8ff-2030e8f2f071" alt=""><figcaption></figcaption></figure>

Nhưng thật ra chúng liên kiên với storage, storeage lại liên kết với folder cố định khác nữa do đó khi upload trên server nó không bị mất ảnh.

### Bước 3: Sử dụng thành quả hiển thị ra ảnh :)

C:\xampp8\htdocs\plugindev\resources\views\use-file.blade.php

```html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <title>Laravel File Upload</title>
  <style>
    .container {
      max-width: 500px;
    }
    dl,
    ol,
    ul {
      margin: 0;
      padding: 0;
      list-style: none;
    }
  </style>
</head>
<body>
  <div class="container mt-5">
    @foreach ($files as $file)
      <div class="row mb-2">
        <img class="img-fluid" src="{{ $file->file_path }}" alt="Text Placeholder">
      </div>
    @endforeach
  </div>
</body>
</html>
```

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FihGdovJu6hraYA5AoKQ5%2Fimage.png?alt=media&#x26;token=5baca9da-4172-49d4-9051-b33b1f6762d6" alt=""><figcaption></figcaption></figure>

### Bước 4: Tạo lệnh php artisan storage:link bằng route

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FvqiQBNmT56lxrk6Vmhx4%2Fimage.png?alt=media&#x26;token=51ca32cf-c004-48e8-98c0-856868cbf820" alt=""><figcaption></figcaption></figure>

```php
Route::get('/foo', function () {
  Artisan::call('storage:link');
});
```

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FhHBBPtBIxiCJuEBj72Ob%2Fimage.png?alt=media&#x26;token=0081f337-56d7-4504-a15f-d2269a6e815a" alt=""><figcaption></figcaption></figure>

## Laravel 9 File Upload Tutorial: Validation + Store in Database

Last updated on: November 25, 2022 by Digamber4.4MSee What's New in Ubuntu MATE 20.04 LTS \[Desktop Tour]![](https://video.primis.tech/uploads/video/users/logo/28561/logo_6130.jpg?cbuster=1567080112)This is a step by step Laravel File Upload tutorial with example, and In this tutorial, we will learn how to upload files in Laravel with basic validation in MySQL database.

This tutorial will cover Laravel file uploading concepts:

* Laravel project Installation
* Route creation and configuration
* Blade file creation
* Database migration in Laravel
* Implement validation on file uploading component
* File uploading status via displaying messages
* Allow uploading only specific file types. e.g .csv, .txt, .xlx, .xls, .pdf with file size limitation max upto 2MB
* Storing an uploaded file in the database

If you are a beginner in Laravel development, you must check out our detailed tutorial on [Building Laravel CRUD Web Application](https://www.positronx.io/php-laravel-crud-operations-mysql-tutorial/).

**Table of Contents**

1. [File Upload in Laravel Example](https://www.positronx.io/laravel-file-upload-with-validation/#tc_9999_01)
2. [Install Laravel Project](https://www.positronx.io/laravel-file-upload-with-validation/#tc_9999_02)
3. [Connect to Database](https://www.positronx.io/laravel-file-upload-with-validation/#tc_9999_03)
4. [Create File Model & Migrations](https://www.positronx.io/laravel-file-upload-with-validation/#tc_9999_04)
5. [Create Routes](https://www.positronx.io/laravel-file-upload-with-validation/#tc_9999_05)
6. [Create File Upload Controller](https://www.positronx.io/laravel-file-upload-with-validation/#tc_9999_06)
7. [Create Blade File](https://www.positronx.io/laravel-file-upload-with-validation/#tc_9999_07)
8. [Conclusion](https://www.positronx.io/laravel-file-upload-with-validation/#tc_9999_08)

### File Upload in Laravel 9 Example

In this Laravel file upload example tutorial, we will generate two routes one for creating a form with getting method and another route for file uploading or post file upload data.

We develop a simple form using Bootstrap and its Form UI component.

It will allow us to choose a file that needs to be uploaded in the **storage > public > uploads** folder. We will also configure the database model and store the file path along with its name in the MySQL database.

### Install Laravel Project

Open command-line tool and execute the following command to create a Laravel project from scratch.

```bash
composer create-project laravel/laravel --prefer-dist laravel-file-upload
```

BashCopy

Get into the freshly installed laravel project’s directory.

```bash
cd laravel-file-upload
```

BashCopy

### Connect to Database

You can use MAMP or XAMPP as a local web server for uploading files to storage in laravel. Define a database name in MySQL and add the correct configuration in `.env` file.

```plsql
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=
```

PL/SQLCopy

If you are using MAMP local server in macOs; make sure to append UNIX\_SOCKET and DB\_SOCKET below database credentials in **.env** file.

```bash
UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
```

BashCopy

### Create File Model & Configure Migrations

Create a Model in laravel, It holds the data definition that interacts with the database.

```bash
php artisan make:model File -m
```

BashCopy

Next, open migration file for defining the table values in the database for storing the uploaded file’s information. Go to **database/migrations/timestamp\_create\_files\_table** file and define the table values.

```php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFilesTable extends Migration
{
    public function up()
    {
        Schema::create('files', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable();
            $table->string('file_path')->nullable();
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('files');
    }
}
```

PHPCopy

Now, add the **$fillable** property in the File model. Open **app/Models/File.php** file and place the following code.

```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'file_path'
    ];
}
```

PHPCopy

Now, you are all set to run the migration. You can also see the update in the mysql database.

```bash
php artisan migrate
```

BashCopy

![Laravel File Upload Example](https://www.positronx.io/wp-content/uploads/2020/06/laravel-file-upload-9999-01.png)

### Create Routes in Laravel

Go to **routes/web.php** and create two routes. First, the route handles the form creation, and the second route stores the file in the MySQL database.

```php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileUpload;
/*
|--------------------------------------------------------------------------
| 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('/upload-file', [FileUpload::class, 'createForm']);
Route::post('/upload-file', [FileUpload::class, 'fileUpload'])->name('fileUpload');
```

PHPCopy

### Create File Upload Controller

Create a file uploading controller; we define the business logic for uploading and storing files in Laravel.

Execute the command to create the controller.

```bash
php artisan make:controller FileUpload
```

BashCopy

Open **app/Http/Controllers/FileUpload.php** file, and we need to define the two methods to handle the file upload.

The first method renders the view via FileUpload controller, and the fileUpload() method checks the validation, be it required, mime type or file size limitation.

This method also stores the file into **storage/public/uploads** folder and saves the file name and path in the database.

```php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\File;
class FileUpload extends Controller
{
  public function createForm(){
    return view('file-upload');
  }
  public function fileUpload(Request $req){
        $req->validate([
        'file' => 'required|mimes:csv,txt,xlx,xls,pdf|max:2048'
        ]);
        $fileModel = new File;
        if($req->file()) {
            $fileName = time().'_'.$req->file->getClientOriginalName();
            $filePath = $req->file('file')->storeAs('uploads', $fileName, 'public');
            $fileModel->name = time().'_'.$req->file->getClientOriginalName();
            $fileModel->file_path = '/storage/' . $filePath;
            $fileModel->save();
            return back()
            ->with('success','File has been uploaded.')
            ->with('file', $fileName);
        }
   }
}
```

PHPCopy

### Create Blade File in Laravel

In this step, we will create a view along with the file uploading form.

Create **resources\views\file-upload.blade.php** file and place the following code inside of it.

```php
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <title>Laravel File Upload</title>
    <style>
        .container {
            max-width: 500px;
        }
        dl, ol, ul {
            margin: 0;
            padding: 0;
            list-style: none;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <form action="{{route('fileUpload')}}" method="post" enctype="multipart/form-data">
          <h3 class="text-center mb-5">Upload File in Laravel</h3>
            @csrf
            @if ($message = Session::get('success'))
            <div class="alert alert-success">
                <strong>{{ $message }}</strong>
            </div>
          @endif
          @if (count($errors) > 0)
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                      <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
          @endif
            <div class="custom-file">
                <input type="file" name="file" class="custom-file-input" id="chooseFile">
                <label class="custom-file-label" for="chooseFile">Select file</label>
            </div>
            <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
                Upload Files
            </button>
        </form>
    </div>
</body>
</html>
```

PHPCopy

This code is responsible for showing file uploading form and also display the message based on the status.

#### Start Laravel Application

To check the demo, execute the following command.

```bash
php artisan serve
```

BashCopy

Check the app on the following Url.

[http://127.0.0.1:8000/upload-file](http://127.0.0.1:8000/upload-file)

![Laravel File Upload Tutorial](https://www.positronx.io/wp-content/uploads/2020/06/file-upload-laravel-9999-02.png)

Finally, we have completed the Laravel File uploading tutorial.
