Upload Multiple Images and Files in Laravel 10 with Validation

In this tutorial, you will learn how to Upload Multiple Images and Files in Laravel with Validation. Uploading multiple files in any project is one of the most commonly used features in web projects.  

You will find how the file uploading system worked in laravel, how we save the data in database along with store the file in a public and storage folder as well as which is generated by symlink. 

laravel-multiple-files-images-upload-tutorial

1. Download Laravel App

In this first step, you need to download or install a fresh laravel 10 application using the following command.

composer create-project --prefer-dist laravel/laravel multiple-files

2. Setup Database

Now you need to open the .env file which is located in your root directory or projecct and update the database credentials such as database name, username, and password.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_multiple_files
DB_USERNAME=root
DB_PASSWORD=

3. Generate Model & Migration File

Now generate a File model and migration file using the below command. It will create a Model file where you can add the fillable properties and in the migration file you need to update the database columns.

php artisan make:model File -m

So, open the app\Models\File.php file and update the following code on it.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    protected $fillable = ['name', 'path'];
}

Next open the database/migrations/2019_08_11_163909_create_files_table.php file and put the below code on it.

<?php 

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

class CreateImagesTable extends Migration { 

/** 
* Run the migrations. 
* 
* @return void 
*/ 

public function up() { 

   Schema::create('files', function (Blueprint $table) { 
            $table->id();
            $table->string('name')->nullable();
            $table->string('path')->nullable();
            $table->timestamps();
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('files');
    }
}

Then, open again command prompt and run the following command to create tables into database:

php artisan migrate

4. Make Routes

Now open your routes/web.php file and update the routes on it.

Now, open the routes/web.php file and add two routes for implementing the Laravel ajax post request. One route will show the form and another is to save the data to the database using ajax request.

<?php

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

Route::get('upload-files', [ FileController::class, 'uploadFiles' ]);
Route::post('upload-files', [ FileController::class, 'storeFiles' ])->name('files.store');


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

5. Create Controller

In this step, run the following command on the command prompt to create controller file.

php artisan make:controller FileController

After that, open the app/http/controllers/FileController.php file and update the following code into it.

<?php

namespace App\Http\Controllers;

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

class FileController extends Controller
{
    public function uploadFiles()
    {

      return view('files');
    }

    public function storeFiles(Request $request)
    {
        $request->validate([
          'files' => 'required',
        ]);

        if ($request->hasfile('files')) {
            $files = $request->file('files');

            foreach($files as $file) {
                $name = $file->getClientOriginalName();
                $path = $file->storeAs('uploads', $name, 'public');

                File::create([
                    'name' => $name,
                    'path' => '/storage/'.$path
                  ]);
            }
         }
         
        return back()->with('success', 'Files uploaded successfully');
    }
}

6. Create Blade File

Now, navigate the resources/views directory and create files.blade.php. After that open the  resources/views/files.blade.php fiel update the following code into it.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Upload Multiple Files in Laravel 7 with Coding Driver</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />


<style>
.invalid-feedback {
  display: block;
}
</style>
</head>
<body>

<div class="container mt-4">
  <h2>Upload Multiple Files in Laravel 7 with- <a href="https://codingdriver.com/">codingdriver.com</a></h2>
    @if(session()->has('success'))
        <div class="alert alert-success">
            {{ session()->get('success') }}
        </div>
    @endif

    <form method="post" action="{{ route('files.store') }}" enctype="multipart/form-data">
      @csrf
      <div class="form-group">
          <input type="file" name="files[]" multiple class="form-control" accept="image/*">
          @if ($errors->has('files'))
            @foreach ($errors->get('files') as $error)
            <span class="invalid-feedback" role="alert">
                <strong>{{ $error }}</strong>
            </span>
            @endforeach
          @endif
      </div>

      <div class="form-group">
        <button type="submit" class="btn btn-success">Save</button>
      </div>
    </form>
</div>
</body>
</html>

NOTE: Run the laravel storage link command for uploading images in public and storage directory.

php artisan storage:link

I hope to Upload Multiple Images in Laravel Tutorial with Example work for you. If you have any questions please comment below.

1 thought on “Upload Multiple Images and Files in Laravel 10 with Validation”

Leave a Comment