Upload Multiple Image Files in Laravel 7

922 VIEWS

This article is about how to upload multiple image files for website development in Laravel 7+ applications.  We explain a step-by-step process of: 

  1. uploading files, 
  2. live preview, and 
  3. validation. 

We also talk about the storage of the same into the database and directory. 

Laravel is a free-to-use, website development open-source web framework based on PHP, developed by Tailor Otwell. It supports the MVC (Model-View-Controller) architectural pattern. It provides an expressive and elegant syntax, useful for creating fully-featured web applications. Read more about Laravel for single page applications.

This post includes how to:

  • Install Laravel App
  • Set up Database
  • Build Routes
  • Create Controller & Methods
  • Create Blade View
  • Start Development Server

#1. Install Laravel App

First, we need to download and install the Laravel fresh setup. Please follow the Laravel documentation for installation depending on your operating system. In this article, we will be using composer, a PHP manager dependency and the Window’s xampp package that comes with the latest version of  PHP, MySQL, and Apache. In case you run into errors during installation, follow the  server requirements manual for guidance.

To install a fresh laravel project setup, we run the following command on the terminal:

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

#2. Set Up Database

On the phpMyAdmin, create a database with your preferred name. Take note of your Xampp server’s username and password.

On the project’s root folder, open the .env file and change the database name and the localhost credentials.

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE= put the name of your database

DB_USERNAME= put the name of your server’s username

DB_PASSWORD= put your server’s password

Generate Migration & Model

Let’s create a table named document and its migration file. Use the following command: 

php artisan make:model document -m

After successfully running the command, go to database/migrations and on the file that contains the name create_documents_table.php file and edit the code to:

<?php




use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;




class CreateDocumentsTable extends Migration

{

   /**

    * Run the migrations.

    *

    * @return void

    */

   public function up()

   {

       Schema::create('documents', function (Blueprint $table) {

           $table->increments('id');

           $table->string('name');

           $table->timestamps();

       });

   }




   /**

    * Reverse the migrations.

    *

    * @return void

    */

   public function down()

   {

       Schema::dropIfExists('documents');

   }

}

Next, migrate the table using the command below:

php artisan migrate

Then, go to app/Document.php model class and edit it by adding the following:

protected $fillable = ['name'];

protected $table = 'documents';

#3. Build Routes

To create routes for multiple file uploads, go to app/routes/web.php. The GET and POST will redirect us to the file uploading view and save the uploaded files respectively.  The web.php file will contain: 

Route::get('/', '[email protected]');

Route::post('save', '[email protected]')->name('save');

#4. Create Controller & Methods

To create a controller named DocumentController, we use the following command :

php artisan make:controller DocumentController

The controller file contains the functions needed to load the page as well as store the data into the database and the storage directory. After successfully creating the controller, go to app/controllers/DocumentController.php and paste code below:

<?php




namespace App\Http\Controllers;




use App\Document;

use Illuminate\Http\Request;

use PhpParser\Comment\Doc;




class DocumentController extends Controller

{




   /**

    * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View

    */

   public function index(){

      return view('document');

  }




   /**

    * @param Request $request

    * @return mixed

    * @throws \Illuminate\Validation\ValidationException

    */

   public function saveDocument(Request $request){




      //validate the files

      $this->validate($request,[

          'image' =>'required',

          'image.*' => 'mimes:jpeg,png,jpg,gif,svg|max:2048'




      ]);

      if ($request->hasFile('image')) {

          $image = $request->file('image');

          foreach ($image as $files) {

              $destinationPath = 'public/files/';

              $file_name = time() . "." . $files->getClientOriginalExtension();

              $files->move($destinationPath, $file_name);

              $data[] = $file_name;

          }

      }

      $file= new Document();

      $file->name=json_encode($data);

      $file->save();




      return back()->withSuccess('Great! Image has been successfully uploaded.');

  }




}

#5. Create Blade View

In this step, we need to create a blade view file which would contain the markup responsible for displaying the form on the interface. Go to app/resources/views and create a new file named document.blade.php. The file will contain the code below:

<!DOCTYPE html>

<html>

<head>

   <title>Laravel 7+ Multiple Image File Upload</title>

   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />

   <style>

       .thumb{

           margin: 10px 5px 0 0;

           width: 300px;

       }

   </style>

</head>

<body>

   <div class="container">

       <div class="row justify-content-center">

           <div class="card" style="margin-top: 4%">




               <div class="card-header bg-secondary dark bgsize-darken-4 white card-header">

                   <h4 class="text-white">Laravel 7+ Multiple Image File Upload with Live Preview</h4>

               </div>

               <div class="card-body">

                   @if ($message = Session::get('success'))




                       <div class="alert alert-success alert-block">




                           <button type="button" class="close" data-dismiss="alert">×</button>




                           <strong>{{ $message }}</strong>




                       </div>

                       <br>

                   @endif

                   <form id="file-upload-form" class="uploader" action="{{url('save')}}" method="post" accept-charset="utf-8" enctype="multipart/form-data">

                       @csrf

                       <input type="file" id="file-input" onchange="loadPreview(this)" name="image[]"   multiple/>

                       <span class="text-danger">{{ $errors->first('image') }}</span>

                       <div id="thumb-output"></div>

                       <br>

                       <button type="submit" class="btn btn-success">Submit</button>

                   </form>

               </div>

           </div>

       </div>

   </div>

</body>




<script>




   function loadPreview(input){

       var data = $(input)[0].files; //this file data




       $.each(data, function(index, file){

           if(/(\.|\/)(gif|jpe?g|png)$/i.test(file.type)){

               var fRead = new FileReader();

               fRead.onload = (function(file){

                   return function(e) {

                       var img = $('<img/>').addClass('thumb').attr('src', e.target.result); //create image thumb element

                       $('#thumb-output').append(img);

                   };

               })(file);

               fRead.readAsDataURL(file);

           }

       });

   }




</script>




</html>

#6. Start Development Server

At this point, our application is ready, so we need to start the website development server. Use the php artisan serve command to start the server. If you want to run the app on a different port, use php artisan serve –port=8080 command.

Once the server has been started, open the project application link on the browser as shown below. Upload a file and it will be saved into the database. http://localhost:8000/

***************

In this tutorial, we have built a simple program to upload and save files into the database and local directory using Laravel. Please pay attention to the following sections of our codes and their explanation:

Laravel File Validation 

Input validation is extremely important in applications as it not only improves app security but it also prevents the users from uploading the wrong data types. In this project, we used controller validation for image uploads to specify the file types and the required size:

$this->validate($request,[

   'image' =>'required',

   'image.*' => 'mimes:jpeg,png,jpg,gif,svg|max:2048'

]);

 

To validate documents, we change the file types as follows:  

$this->validate($request,[

   ‘filename’=>'required',

   ‘filename.*' => 'mimes:pdf,doc,docx,pdf,txt|max:2048'

]);

Laravel File Storage

Laravel provides different ways to store your uploaded data, either on the same project server or on the cloud. In our case above, we stored the uploaded files inside the files folder within  the base public directory. To ensure consistency, we store the files by their original names and the time they were uploaded. 

 

if ($request->hasFile('image')) {

   $image = $request->file('image');

   foreach ($image as $files) {

       $destinationPath = 'public/files/';

       $file_name = time() . "." . $files->getClientOriginalExtension();

       $files->move($destinationPath, $file_name);

       $data[] = $file_name;

   }

}

$file= new Document();

$file->name=json_encode($data);

$file->save();

Laravel File Upload Form and Preview

The upload form is next. For that, we need to specify how the browser will format the request by including the

 enctype="multipart/form-data" 

and

method="POST". 

We also need to include:

 {{ csrf_field() }} 

This helps Laravel in protecting your application from cross-site request forgery. Laravel does this by generating a hidden input field with a token that verifies the legitimacy of form submission. 

To preview the image before submitting, this JavaScript function uses a fileReader to append the image on the interface. 

if ($request->hasFile('image')) {

   $image = $request->file('image');

   foreach ($image as $files) {

       $destinationPath = 'public/files/';

       $file_name = time() . "." . $files->getClientOriginalExtension();

       $files->move($destinationPath, $file_name);

       $data[] = $file_name;

   }

}

$file= new Document();

$file->name=json_encode($data);

$file->save();

This is how the images will appear as you upload them:

Multiple image file uplaod Laravel 7

We hope you find this information helpful in your website development projects. You can read more about Getting Started with Laravel, here. Thank you for following. Find the full code here

 


Faith is a curious software engineer and a data science enthusiast, with a passion for problem-solving through implementation of high-quality software products. She holds a Bachelor’s degree in Computer Science from Ashesi University. She has experience working in academia, fin-tech, healthcare, research, technology, and consultancy industries both in Kenya and Ghana. She combines her passion for teaching, technology and writing to create technical digital content.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

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

%d bloggers like this: