In Laravel 8 you can upload single as well as multiple images. The image has attributes like extension, size, and the temp name. We can upload and store image name into the database. Also, we can replace the original image name. This will overcome the repetition of the image name from the previously uploaded. Previously, I have shared the tutorial on Laravel 8 image upload with validation. Today, through this post, you will be learning the Laravel 8 multiple images upload. So, let’s continue to the project.
Prerequisites
For creating multiple images in Laravel 8, we will create a new project. To create this project, you will require the following tools-
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
Create Project For Laravel 8 Multiple Images Upload
We will create the Laravel 8 project using the composer. So, open the terminal and create the project.
composer create-project --prefer-dist laravel/laravel image-upload
Once project has been created, let’s configure the database.
Laravel 8 Form Validation Tutorial For Beginners
Create and Configure Database
I am using the MySQL command line for the database. So, you will have to create a database by hitting the below command.
CREATE DATABASE image_upload;
After creating the database, let’s configure the database for the project.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=image_upload
DB_USERNAME=root
DB_PASSWORD=root
Now, the database has been configured and synced with the project. In the next step, we’ll be creating a model and migration.
Laravel 8 CRUD Application Tutorial From Scratch
Create a Model, Migration and Controller
We will create a model, migration and controller in a single line of command.
php artisan make:model Image -mc
The above command will create a model, a migration and a controller. In the migration, add the below code to change the schema for the table.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateImagesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('image_name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('images');
}
}
Now, specify the fillable data for the created model. I have set the image_name as the mass assignment in this model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
protected $fillable = [
"image_name"
];
}
Once the migration and the fillable data has completed, let’s migrate the table.
php artisan migrate
The migration will generate the tables in the database.
Now, the tables are ready therefore add the functionality for Laravel 8 multiple images upload.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
class ImageController extends Controller
{
public function index() {
return view('image-upload');
}
// ---------- [ Upload image ] ---------
public function uploadImage(Request $request) {
$validator = $request->validate([
'images' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'images.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$files = array();
if($request->hasfile('images'))
{
foreach($request->file('images') as $image)
{
$name = time().rand(1,100).'.'.$image->extension();
if($image->move(public_path('uploads'), $name)) {
$files[] = $name;
$upload_status = Image::create(["image_name" => $name]);
}
}
}
if(!is_null($upload_status)) {
return back()->with('success', 'Success! images uploaded');
}
else {
return back()->with('failed', 'Alert! images not uploaded');
}
}
}
In the first function, I have called the view. So, we will create a view for it. But, now, moving to the next function. In the next function, I have read out the array of images. Then created the file name using the timestamp and rand() function. It will generate a unique string for every image name.
Then using the loop iteration, extracted the single image and storing it into the table. That’s it for the function.
Now, for the next step, add routes for the functions.
Create a CRUD App in React.js Using Laravel 7 RESTful API
Add Web Routes in Laravel 8
We will add the routes in the web.php file.
<?php
use App\Http\Controllers\ImageController;
use Illuminate\Support\Facades\Route;
Route::get('image', [ImageController::class, 'index']);
Route::post('image/upload', [ImageController::class, 'uploadImage']);
After adding the routes move to the next step. So, next, create a view inside the resources/views folder.
How to Implement Yajra DataTable in Laravel 7
Create a View to Upload Multiple Images in Laravel 8
Here, we will create a view with the name image_upload.blade.php. Then add the below snippet, it will create a form for you.
<!doctype html>
<html lang="en">
<head>
<title> Laravel 8 Image Upload - Programming Fields</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" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-xl-6 col-lg-6 m-auto">
<form action="{{url('image/upload')}}" method="POST" enctype="multipart/form-data">
@csrf
<div class="card shadow">
@if(Session::has('success'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
{{Session::get('success')}}
</div>
@elseif(Session::has('failed'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
{{Session::get('failed')}}
</div>
@endif
<div class="card-header">
<h4 class="card-title"> Laravel 8 Image Upload </h4>
</div>
<div class="card-body">
<div class="form-group">
<label for="file"> Image <span class="text-danger">*</span> </label>
<input type="file" name="images[]" multiple class="form-control">
{!!$errors->first("images", "<span class='text-danger'>:message</span>") !!}
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success"> Upload </button>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
For uploading the multiple images, you will have to specify the name attribute to an array. Also, you will have to give attribute multiple. So, that it can hold multiple images and you can select multiple images from the folder.
Save and run the application to get the result.
Firstly, we will check for the validation. So, at this time, I haven’t selected any images or files and hit the upload button.
Now, in the response, I have the validation error message.
How to Create Auth with Jetstream and Livewire in Laravel 8
Secondly, I have selected the 4 images. As you can see in the selected list.
Now, as a result, we have a successful response. The selected images have been uploaded.
How to Implement Google Charts in Laravel 7
Conclusion
We have implemented Laravel 8 multiple images upload functionality. Also, we have set the validation before uploading the images. Once, the validation criteria will be passed, the selected images will be moved to the public folder. After moving the file, the images name will be inserted into the database table. So, I hope this will a quick guide for you. You can extend it further as per your project requirements. Thank you.
Diwakar Kumar says
All working good but had you tried to upload files with different mime types that are not allowed in the validation for e.g. .pdf file. The validation works but the message didn’t show.
Umesh Rana says
'file' => 'required|mimes:doc,docx,pdf|max:2048'
Also, you can check by putting a custom validation message.