Multiple File Upload Laravel 9 Tutorial

Multiple files upload in laravel 8=9

In this appfinz tutorial series, you will get to learn how to upload multiple files in laravel 9. you’ll learn to upload multiple files in PHP laravel 9. this tutorial series will help you to understand about multiple file upload laravel 9. I would like to share with you laravel 9 multiple file upload example.

In the very first step, we will create simple multiple file upload in laravel 9. So you basically use this code on your laravel 9 application.

We are going from starch so, we will upload multiple files and store them on the server then after we will store the database too. so in this example, we will create a “files” table using laravel migration and write code for route, controller, and view step by step.

  • Step 1 – Install Laravel 9 Application
  • Step 2 – Configuring Database Details
  • Step 3 – Create Model & Migration
  • Step 4 -Create Upload Routes
  • Step 5 – Creating Upload Controller
  • Step 6 – Create Multiple File Upload Form
  • Step 7 – Run This App On Browser

Step1: Download Laravel 9 on your System

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 9 latest application using the following command:

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

Step 2 – Configuring Database Details

In step 2, open your downloaded laravel 8 apps into any text editor. Then find the .env file and configure database detail like the 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 Model & Migration

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

Then create a 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 9 applications for the multiple file upload tutorial apps, which is located inside the following locations:

  • multiplefiles/app/Models/File.php
  • multiplefiles/database/migrations/create_file_table.php

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

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

and then in this laravel 9 multiple files upload tutorial next step you need to migrate all the tables using this command

php artisan migrate

Step 4 – Create Upload Routes

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

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

Route::post('/post-multiple-image', [App\Http\Controllers\FileController::class, 'multiple']);

Step 5: Creating File Controller

in this step, create a file controller using following command

php artisan make:controller FileController

The above command will create the FileController.php file, which is located inside multiplefiles/app/Http/Controllers/ directory.

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

        $this->validate($request, [
            'image' => 'required',
            'image.*' => 'mimes:doc,pdf,docx,zip'
    ]);
<?php

namespace App\Http\Controllers;
use DB;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Str;

class FileController extends Controller
{
    public function multiple(Request $request)
	{
        $this->validate($request, [
            'image' => 'required',
            'image.*' => 'mimes:doc,pdf,docx,zip'
    ]);

        if ($request->file('image')) {
            foreach ($request->file('image') as $photo) {
                  $file      = $photo;
                  $filename  = Str::random(40);
                  $upload_path ='public/image/';
                  $extension = strtolower($file->getClientOriginalExtension());
                  $picture     = $upload_path.$filename.'.'.$extension;
                  $pictures[]   = $picture;

            //Save files in below folder path, that will make in public folder
                  $file->move(public_path('images/'), $picture);
                  $postArray = ['fname' => $picture,];
                  DB::table('file')->insert($postArray);
                  }
                  return redirect::back();
        }
    }

}

Step 6: Create a Blade file for showing our Multiple files upload form

we are using the existing welcome.blade.php file here, you can change or modify it according to your need.

then create Multiple files upload form inside our welcome.blade.php

<!DOCTYPE html>
<html lang="en">
<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>Document</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.min.js" integrity="sha384-ODmDIVzN+pFdexxHEHFBQH3/9/vQ9uori45z4JjnFsRydbmQbmL5t1tQ0culUzyK" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
</head>
<body>

    <div class="container pd90 mt-90" style="padding-top:50px;">
        <div class="row">
<div class="col-md-6">
    <div class="mb-3">
        <form role="form" method="post" action="{{url('/post-multiple-image')}}" enctype="multipart/form-data">
            {{csrf_field()}}
        <label for="formFile" class="form-label">Upload Multiple Image</label>
        <input class="form-control custom-file-input" name="image[]" multiple type="file" id="formFile">
        <button type="submit" class="btn btn-primary mt-2">Submit</button>
    </form>
      </div>

</div>
        </div>
    </div>

    <script type="text/javascript">
        $(function () {
          $(document).on('click', '[data-toggle="lightbox"]', function(event) {
            event.preventDefault();
            $(this).ekkoLightbox({
              alwaysShowClose: true
            });
          });

        });
      </script>
</body>
</html>

Conclusion: we have made a simple multiples files upload in laravel 9, you can use this method in other laravel versions too. we are here trying to upload multiple images through our file. you can also try to insert multiple files using the same way. if you still have any problem feel free to connect with me.

Comment below your thoughts and suggestions, if you want any specific topic blog then feel free to write me, our team will available to guide you further.

About Post Author

Leave a Reply

Your email address will not be published. Required fields are marked *