Multiple Images Upload in Laravel with Validation
Many developers face difficulties in adding image upload feature in the application. Specifically, developers are uncertain about how to upload and validate images. In this post, you will learn how to implement Laravel multiple image upload functionality with validations.
Create Laravel Project
To create a Laravel app, run the following command in the terminal:
composer create-project laravel/laravel --prefer-dist laravel-app
cd laravel-app
Database Configuration
Create database and define your database configuration in .env
file.
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=
Create Image Model and Migrations
To create Image model and images table migration use following command:
php artisan make:model Image -m
Now go to the database/migration
directory and open the migration file for the images
table. In this migration, add column image_path
.
<?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_path')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('images');
}
}
Next, run the migration to create tables in the database.
php artisan migrate
Create Routes in Laravel
Go to routes/web.php
and create two routes. One route to show image upload form, and the second route is to upload the image.
// Create image upload form
Route::get('/images/upload', 'ImageUploadController@show');
// Store image
Route::post('/images/upload', 'ImageUploadController@store')->name('images.store');
Create Image Uploading Controller
Run the following command to create ImageUploadController
:
php make:controller ImageUploadController
Next, in the Go to app/Http/Controllers/ImageUploadController.php
file, we need to create a show()
method to display image upload form and store()
method to upload images as shown in the following code snippet:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Image;
class ImageUploadController extends Controller
{
public function show()
{
return view('images.show');
}
public function store(Request $request)
{
$request->validate([
'file' => 'required|image|max:2048'
]);
$imageModel = new Image;
if($request->file()) {
$imagePath = $request->file('file')->store('uploads');
$imageModel->image_path = '/uploads/' . $imagePath;
$imageModel->save();
return back()
->with('success','Image has been uploaded.')
->with('file', $imagePath);
}
}
}
Create Blade Template for image upload form
Create resources\views\images\show.blade.php
file and add the following code.
<!doctype html>
<html lang="en">
<head>
<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.5.0/css/bootstrap.min.css">
<title>Laravel Image Upload</title>
<style>
.container {
max-width: 500px;
}
dl, ol, ul {
margin: 0;
padding: 0;
list-style: none;
}
.imgPreview img {
padding: 8px;
max-width: 100px;
}
</style>
</head>
<body>
<div class="container mt-5">
<h3 class="text-center mb-5">Image Upload in Laravel</h3>
<form action="{{route('imageUpload')}}" method="post" enctype="multipart/form-data">
@csrf
@if ($message = Session::get('success'))
<div class="alert alert-success">
<strong>{{ $message }}</strong>
</div>
@endif
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="user-image mb-3 text-center">
<div class="imgPreview"> </div>
</div>
<div class="custom-file">
<input type="file" name="imageFile[]" class="custom-file-input" id="images" multiple="multiple">
<label class="custom-file-label" for="images">Choose image</label>
</div>
<button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
Upload Images
</button>
</form>
</div>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script>
$(function() {
// Multiple images preview with JavaScript
var multiImgPreview = function(input, imgPreviewPlaceholder) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(imgPreviewPlaceholder);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#images').on('change', function() {
multiImgPreview(this, 'div.imgPreview');
});
});
</script>
</body>
</html>
Finally, we have completed the Laravel Image upload feature. Its time to run this in browser. So, in your terminal run following command:
php artisan serve
Now test this URL path (http://127.0.0.1:8000//images/upload
) in your browser.
Please login or create new account to add your comment.