As similar to a single image upload, you can upload multiple images in Laravel 10. The file input provides an attribute named multiple, allowing us to choose multiple images. After selecting multiple images, you can handle the form request in the controller. In multiple images upload basically, the images will be passed in the form of an array. According to the images, you need to extract the images from the images array. The images will be uploaded one by one from the array list.
We are going to cover up the multiple images upload as shown below in this example.
We will validate the images before upload. The selected file must be an image.
If the selected images will be uploaded then you will be getting success response as shown below.
Therefore, let’s jump on the example quickly.
How to Upload Image in Laravel 10 with Validation
Prerequisites
We will be implementing functionality to upload multiple images in Laravel 10. If you don’t have a Laravel 10 application, then you may create a new one. However, in order to create a Laravel 10 project, you will be needing the below tools and configurations.
- PHP >=8.1
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
Once, you are done with the above requirement, let’s have a Laravel 10 project. I am assuming you already have a Laravel 10 project setup. Hence, without wasting your time, let’s jump on the functionality directly.
Create a Model and Migration to Upload Multiple Images in Laravel
Navigate to the terminal and hit the below command to create a model and migration with a controller. We will be passing the controller flag as well.
php artisan make:model Image -mc
After generating these files, let’s quickly add the schema to the migration file.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('image_name')->nullable();
$table->string('image_original_name')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('images');
}
};
Next, you need to migrate the above migration schema using the below command.
php artisan migrate
After that, you have to add the fillable property inside the model.
Add Mass Assignment in Model
Navigate to the model and add the below snippet inside it.
<?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',
'image_original_name',
];
}
After adding the fillable property, let’s work on the functionality part.
How to Create a CRUD Application Using Ajax in Laravel 10
Add Functionality For Multiple Images Upload
Navigate to the ImageController file and add the below functions. Take a look at the upload() function, I have added validation rules for multiple images in the form of an array. As we made the name attribute to array in order to read multiple images from the form.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
class ImageController extends Controller
{
/**
* Display a listing of the resource.
*/
public function create()
{
return view('image-upload');
}
/**
* Upload image and save image name.
*/
public function upload(Request $request) {
$validatedData = $request->validate([
'images' => 'required',
'images.*' => 'required|image|mimes:jpeg,png,jpg,svg|max:2048'
]);
$images = array();
if ($request->hasfile('images')) {
foreach($request->file('images') as $image) {
$imageName = time().rand(1,100).'.'.$image->extension();
$imageOriginalName = $image->getClientOriginalName();
if($image->move(public_path('uploads'), $imageName)) {
$images[] = $imageName;
$image = Image::create([
"image_name" => $image,
'image_original_name' => $imageOriginalName,
]);
}
}
}
if (count($images) > 0) {
return back()->with('success', 'Success! Images have been uploaded');
}
else {
return back()->with("failed", "Alert! Unable to upload image");
}
}
}
Next, you need to add roues as per the above functions.
How to Validate a Form Using Form Validator in Laravel 10
Add Web Routes
For adding the web routes, navigate to the web.php file and add the below routes.
<?php
use App\Http\Controllers\ImageController;
use Illuminate\Support\Facades\Route;
Route::get('images', [ImageController::class, 'create'])->name('images');
Route::post('images', [ImageController::class, 'upload'])->name('images.store');
Now, let’s work on the form part. You need to create a view in which there will be a form with the input type of file and button.
Create a View For Images Upload in Laravel 10
At last, you need to create a view from there you will be uploading the images. Hence, create a view named image-upload.blade.php
.
After creating the blade file, let’s put the below snippet to render a form with the input file and button.
<!doctype html>
<html lang="en">
<head>
<title> Laravel 10 Multiple Images Upload with Validation - 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://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-xl-8 col-md-8 col-sm-12 m-auto">
<form action="{{ route('images.store') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="card shadow">
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<symbol id="check-circle-fill" fill="currentColor" viewBox="0 0 16 16">
<path
d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z" />
</symbol>
<symbol id="exclamation-triangle-fill" fill="currentColor" viewBox="0 0 16 16">
<path
d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
</symbol>
</svg>
{{-- Display alert message --}}
@if (Session::has('success'))
<div class="alert alert-success alert-dismissible d-flex align-items-center" role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Success:">
<use xlink:href="#check-circle-fill" />
</svg>
<div>
{{ Session::get('success') }} <button type="button" class="btn-close" data-bs-dismiss="alert"
aria-label="Close"></button>
</div>
</div>
@elseif (Session::has('error'))
<div class="alert alert-danger d-flex alert-dismissible align-items-center" role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Danger:">
<use xlink:href="#exclamation-triangle-fill" />
</svg>
<div>
{{ Session::get('error') }} <button type="button" class="btn-close" data-bs-dismiss="alert"
aria-label="Close"></button>
</div>
</div>
@endif
<div class="card-header">
<h4 class="card-title fw-bold"> Laravel 10 Multiple Images Upload</h4>
</div>
<div class="card-body">
<div class="form-group">
<label> Image(s) </label>
<input type="file" name="images[]" class="form-control @error('images') is-invalid @enderror" multiple>
@error('images')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary"> Upload </button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
That’s it. Now, you can run the application to check the result of multiple images upload in Laravel 10.
php artisan serve
After running the application, access the URL in the browser and see the result.
Leave a Reply