To upload multiple images in Laravel 9, you can form an array of images. The array will contain more than one item (image). So, it will allow us to extract the image from the array. Also, the image will be uploaded one by one. You can store the file name in the database. The most important thing is to validate the image. As we have seen in the last post with a single image upload in Laravel 9. In this post, we will upload multiple images in Laravel 9.
We will set a validation rule to check the images. So, there will be a required field validation. Also, will check the mime type.
You can select multiple images here. This is not a drag and drop. Hence, you have to select the image(s) by selecting using shift-click.
If the images will be uploaded then you will have a successful response as shown below.
At the end of this post, we will achieve the above results. Hence, let’s start quickly by creating a project.
How to Create a Dependent Dropdown in Laravel 8 Using Ajax
Prerequisites
To proceed with a Laravel 9 project, your system must meet the below configurations.
- PHP >=8.0.2
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
Create Project in Laravel 9 to Upload Multiple Images
For creating a new project firstly open the command prompt. You can create a project by hitting the below command.
composer create-project --prefer-dist laravel/laravel blog
Once you created the project, let’s have the database configuration.
How to Create Custom Password Reset Link in Laravel 8
Configure Database in Laravel 9
Navigate to the .env file and add the database configuration.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=DATABASE_NAME
DB_USERNAME=DATABASE_USERNAME
DB_PASSWORD=DATABASE_PASSWORD
Replace your database credentials here. In the next step, let’s create a model, migration, and controller.
Pass Data to Master Layout By Service Provider in Laravel 8
Create a Model and Migration to Upload Multiple Images
The below command will create a model, migration, and a controller.
php artisan make:model Image -mc
Firstly, navigate to the migration file and add the below snippets.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('imageName');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('images');
}
};
After that, you have to migrate the database. Therefore, hit the below command.
php artisan migrate
Once the table has been created, let’s add a mass assignment to the model.
Redirect HTTP to HTTPS Using Middleware in Laravel 8
Add Fillable Data in Model in Laravel 9
Navigate to the Image.php (model) and add the fillable property as shown below.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
protected $fillable = [
'imageName'
];
}
Next, you have to add the functionality of uploading multiple images.
Create REST API in Laravel 8 Using JWT Authentication
Upload Multiple Images in Laravel 9
Navigate to the created controller. Now, paste the below code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
class ImageController extends Controller
{
/**
* Return image upload view
* @param request
* @return response
*/
public function index() {
return view('image-upload');
}
/**
* Upload image
* @param request
* @return response
*/
public function upload(Request $request) {
$validator = $request->validate([
'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(["imageName" => $name]);
}
}
}
if($upload_status) {
return back()->with('success', 'Success! images uploaded');
}
else {
return back()->with('failed', 'Alert! images not uploaded');
}
}
}
After adding the functionalities, you have to add routes respectively.
How to Create Github Login in Laravel 8 Using Socialite
Add Routes in Laravel 9
For adding the routes, you have to open the web.php file.
<?php
use App\Http\Controllers\ImageController;
use Illuminate\Support\Facades\Route;
Route::get('image', [ImageController::class, 'index'])->name('image');
Route::post('image', [ImageController::class, 'upload'])->name('image');
At last, you have to create a blade file. This view will contain the form. The form will have an input of a type file with multiple upload options.
Create a View for Uploading Multiple Images
For uploading images, we will require a view. So, create a view named image-upload.blade.php file.
<!doctype html>
<html lang="en">
<head>
<title> Laravel 9 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://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-6 col-md-6 col-sm-12 m-auto">
<form action="{{ route('image') }}" 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="btn-close" data-dismiss="alert">×</button>
{{Session::get('success')}}
</div>
@elseif(Session::has('failed'))
<div class="alert alert-danger alert-dismissible">
<button type="button" class="btn-close" data-dismiss="alert">×</button>
{{Session::get('failed')}}
</div>
@endif
<div class="card-header">
<h4 class="card-title fw-bold"> Laravel 9 Multiple Images Upload </h4>
</div>
<div class="card-body">
<label for="file"> Image(s) <span class="text-danger">*</span> </label>
<input type="file" name="images[]" multiple class="form-control @error('images') is-invalid @enderror">
@error('images')
<div class="invalid-feedback">{{ $message }} </div>
@enderror
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success"> Upload </button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
That’s it for the functionality. Now, you can test the result by running the application.
Conclusion
We covered the functionality to upload multiple images in Laravel 9. In the view file, we formed an array of images. After submitting the form, we handled it in the controller. In the controller, we validated image(s). After validation, we extracted the image and uploaded them one by one. Finally, we stored the image name in the database as well. So, I hope this post will be helpful for you.
Leave a Reply