Multiple file uploads provide an easy way to upload more than one file at the same time. This allows us to select and upload multiple files/images. In Laravel 6, we can upload multiple images with validation easily. In the process of multiple image upload, an array of the file will be created. Then according to the length of the array, the file will be uploaded. I have already shared a post on Upload Single File and Image in Laravel 6. In that post, I had implemented the functionality of a single file and image upload. But, in this post, I will be showing you how to achieve multiple image upload in Laravel 6.
Prerequisites
For creating any Laravel 6 project, you must have a system configured with PHP >= 7.2.0 version and MySQL database 8. Also, your system will need a PHP server like Apache or Nginx.
When you are done, then let’s create a new project in Laravel 6.
Drag and Drop File Upload in Laravel 6 Using Dropzone js
Multiple Image Upload in Laravel 6
In this post, I will be showing you how you can achieve multiple image upload in Laravel 6. For, this I will create a form using the Bootstrap. That will be called as a View. So, just go ahead step by step.
So, let’s start by creating a new project set up in Laravel 6. Just enter the below command in the terminal and wait for creating the project.
composer create-project --prefer-dist laravel/laravel laravel6-multiple-image-upload
How to Resize Image in Laravel 6 Before Upload
Create a MySql Database
When you are ready with your project, it’s time to create a new database. I am going to use MySQL 8 here. So, let’s create a new database. You can use command prompt or GUI as well.
CREATE DATABASE laravel6_img_upload;
Configure Database in Laravel 6
In the next step, you will have to configure the database authorization. For this, you will need to replace the below details from the .env file of your project.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel6_img_upload
DB_USERNAME=root
DB_PASSWORD=root
How to Implement Pagination in Laravel 6 with Example
Create Model and Migration
For implementing multiple image upload in Laravel 6, you will need a Model. Also, with the model, we will be creating a migration. The migration holds the schema of the table.
php artisan make:model ImageUpload --migration
This command will generate a Model with the name ImageUpload. Also, with this model, a database table schema will be associated.
You can find the migration file inside the database folder of the project. Now, add one more field in the existing schema.
// create_image_uploads_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateImageUploadsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('image_uploads', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('image_name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('image_uploads');
}
}
How to Use AJAX in Laravel 6 with ToDo Application
Add Fillable Data in the Model
In the Laravel 6, we will have to define the columns (fields) of the table which are going to be inserted using the eloquent. So, in our case, we have the image table in which we are going to insert the image name. So here, we have a single field that will gonna add here in the model.
// ImageUpload.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ImageUpload extends Model
{
protected $fillable = [ 'image_name' ];
}
Laravel 6 REST API For ToDo Application with Passport Auth
Migrate Table Schema
Once, you have created the schema, let’s migrate it. The migration will create the tables inside the configured database. Also, inside the table, all the specified fields will be created there.
php artisan migrate
In the database, you have now the tables which are migrated.
Create a Controller For Multiple Image Upload in Laravel 6
For proceeding the multiple image upload in Laravel 6, we will need a controller. The controller will hold the function for uploading the images. So, open the terminal and enter the command.
php artisan make:controller ImageUploadController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\ImageUpload;
use Illuminate\Support\Facades\Validator;
class ImageUploadController extends Controller
{
public function index() {
return view('upload');
}
// ------------------ [ Upload image ] --------------
public function uploadImages(Request $request) {
// file validation
$this->validate($request, [
'images.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
// if validation success
$images = array();
if($files = $request->file('images')) {
foreach($files as $file) {
$name = time().'.'.$file->getClientOriginalExtension();
$destinationPath = public_path('/uploads');
if($file->move($destinationPath, $name)) {
$images[] = $name;
$saveResult = ImageUpload::create(['image_name' => $name]);
}
}
return back()->with("success", "File uploaded successfully");
}
}
}
How to Send Email in Laravel 6 Via Gmail Using SMTP
Create Routes
For multiple image upload functions, we need to specify the routes. These routes will be defining which function will be called on the specified URL. So, in the web.php file, add these two routes.
// web.php
Route::get('/', 'ImageUploadController@index');
Route::post('upload-images/', 'ImageUploadController@uploadImages');
Once you have added the routes, let’s create the views for uploading the multiple images.
Create Views
According to this project, we need only one view. That is for uploading multiple images. So, in the resources/views folder create a blade file and put the name upload.blade.php.
<!-- upload.blade.php -->
<!doctype html>
<html lang="en">
<head>
<title>Laravel 6 - Multiple Images Upload </title>
<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.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-8 col-sm-12 col-12 m-auto">
<form action="{{ url('upload-images') }}" method="post" enctype="multipart/form-data">
@csrf
<div class="card shadow">
<div class="card-header bg-success">
<h5 class="text-white"> Laravel 6 Multiple Images Upload </h5>
</div>
<div class="card-body">
<!-- print success message after file upload -->
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
@php
Session::forget('success');
@endphp
</div>
@endif
<label for="images"> Images </label>
<div class="form-group">
<input type="file" name="images[]" class="form-control" id="images" multiple/>
{!! $errors->first('images', '<small class="text-danger">:message</small>') !!}
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success"> Upload Images </button>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body>
</html>
Once you have created the view. Let’s check how does it look?
So, just open the browser, and hit the first route that we have specified above.
http://localhost:8000/
In the controller, I have set the index function to the home. So, when you will enter the above URL in the browser, it will return the result.
Now, select multiple images by choosing the files. You can see here, I have chosen 3 images in the result.
In the next step click on the Upload Images button. The images will be uploaded successfully.
As a result, you can see the images have uploaded in the public/uploads folder. Also, I have inserted the image name into the database table.
Conclusion
In the multiple image upload, we create an array of the input type file. That allows us to select multiple files or images. Once, we have selected the multiple images, the image array will pass to the controller. Again in the controller, we extract the array data using the for each loop. So, the loop will iterate on the length of the array. On every iteration of the loop, the image will be uploaded and the image data will be stored in the database. That’s it. So, I assume this one will be an easy step for you to achieve. But, if you got any error or if you have any doubt then don’t forget to drop your comments. Thank you.
Rohit says
Tremendous article on multiple images upload in Laravel 6. Very simple explanation. Helpful for beginners.
motin says
ok its work. but problem is how to select multi image to upload. I’m tried but not success.
Umesh Rana says
Use Ctrl+mouse click to select the multiple images.
Jari Rindu says
Hello, what if I want to upload two photos (using two form) in a single table in the database? Each 1 photo only 1 form.
Umesh Rana says
Simply remove attribute multiple from the input type file. Then by default, it will allow you to upload a single file at a time. Do the same thing for both form (form1, form2). Then after upload, just insert the file name from both form one by one into the database.