Laravel 9 - Upload multiple image
Laravel 9 - Upload multiple image
In this tutorial, we will discuss how to upload multiple images in Laravel 9. Uploading multiple images is useful for handling batch uploads, such as managing user galleries, product images, or bulk media submissions. It streamlines the process of managing and organizing multiple files in a single operation.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
In this guide, we walk through implementing multiple image uploads in a Laravel 9 application. We start by creating a fresh Laravel project and setting up the development environment with Vite. Next, we generate a model, migration, and controller to manage image data. A database table is defined with appropriate columns, and a Blade view is created to display the upload form. Routes are then added to handle both form display and image submission. Finally, we test the functionality by running the Laravel server and uploading multiple images, which are stored in the public/image directory and recorded in the database. This step-by-step process ensures a clean, organized, and functional multiple image upload system.
Step # 1 : Set Up a Fresh Laravel 9 Project.
To get started, let’s create a clean Laravel 9 application. If you have Laravel installed globally, run.
laravel new multipleImages
Or, if you prefer Composer, use.
composer create-project laravel/laravel --prefer-dist multipleImages
This will generate a brand-new Laravel project with the default structure and all necessary files. Once set up, you’ll have a fresh workspace to start building your front-end and implementing multiple image upload functionality. Starting with a clean project ensures a stable foundation, free from conflicts or leftover configurations from previous projects.
Step # 2 : Navigate to Your Project and Start the Dev Server.
After creating the Laravel project, open your terminal (for example, Git Bash) and move into your project’s root directory.
cd c:xampp/htdocs/multipleImages
Next, install the necessary dependencies and start the Laravel Vite development server to handle your front-end assets.
npm install && npm run dev
It’s a good idea to open a second terminal window or tab, navigate to the same project folder, and keep it ready for running additional Laravel commands while the dev server runs in the background. This ensures your front-end assets are compiled and ready for development as you build your multiple image upload functionality.
Step # 3 : Generate Model, Migration, and Controller for Images.
Next, we’ll set up the backend structure to manage multiple images. Laravel makes this easy with a single Artisan command.
php artisan make:model Image -cm
This command accomplishes three tasks in one go. It creates a Model named Image to interact with the database, generates a Migration file to define the table structure for storing image details, and creates a Controller to handle the logic for uploading, saving, and managing images. By generating these components together, you set up a clean and organized workflow for efficiently handling multiple image uploads in your Laravel application.
Step # 4 : Define Columns and Make Them Fillable.
Now, let’s set up the database table to store image information. Open the migration file create_images_table.php and update the up method as follows.
public function up(): void
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('name'); // Column to store image file name
$table->timestamps();
});
}
Since we’ll be inserting data through a form, we need to make these fields mass assignable. Open the Image model and add the $fillable property.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
// Allow mass assignment for the 'name' field
protected $fillable = [
'name',
];
}
Finally, run the migration to create the table in your database.
php artisan migrate
This sets up a structured table for storing image information and ensures Laravel can safely handle form submissions.
Step # 5 : Create the Upload Form View.
To allow users to upload multiple images, we need to create a Blade view. Inside the resources/views directory, create a file named upload-image.blade.php and add the following code.
<!DOCTYPE html>
<html>
<head>
<title>Laravel 9 - Code Shotcut Upload Multiple Images</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading mb-3 mt-5">
<h2>Laravel 9 - Upload Multiple Images</h2>
</div>
<div class="panel-body">
@if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<strong>{{ $message }}</strong>
</div>
@endif
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ url('/upload-images') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="row">
<div class="mb-3 col-md-6">
<label class="form-label">Select Images:</label>
<input type="file" name="images[]" class="form-control" multiple/>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-success">Upload Image/Images</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
The form includes some essential fields: the enctype="multipart/form-data" attribute ensures that the form data, including file uploads, is properly encoded for submission. The <input type="file" name="images[]"> field allows users to select multiple files at once, enabling seamless upload of multiple images in a single submission.
Step # 6 : Add Methods in the ImageController.
Next, we’ll define the logic to display the upload form and handle multiple image uploads. Open the ImageController.php file and add the following methods.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
class ImageController extends Controller
{
// Display the upload form
public function index()
{
return view('upload-image');
}
// Handle multiple image uploads
public function store(Request $request)
{
// Validate each uploaded image
$request->validate([
'images.*' => 'required|mimes:png,gif,jpg,bim|max:2048',
]);
// Check if images are present
if($request->images)
{
foreach ($request->images as $image) {
// Rename image with timestamp to avoid conflicts
$modifiedImage = time() . ' - ' . $image->getClientOriginalName();
// Move the uploaded image to the public/image directory
$image->move(public_path('/image'), $modifiedImage);
// Save image information in the database
Image::create([
'name' => $modifiedImage,
]);
}
}
// Redirect back with success message
return back()->with('success', 'Images uploaded successfully.');
}
}
The index method returns the Blade view for the upload form. The store method validates each uploaded image, renames it to prevent conflicts, saves the file to the public/image directory, and records the filename in the database. Finally, it redirects back with a success message once all images are uploaded.
Step # 7 : Define Routes for Image Upload.
To make the upload form and image submission work, we need to define routes in routes/web.php. First, import the ImageController at the top of the file.
use App\Http\Controllers\ImageController;
Then, add the following routes.
// Display the upload form
Route::get('/upload', [ImageController::class, 'index']);
// Handle the form submission and store images
Route::post('/upload-images', [ImageController::class, 'store']);
These routes connect your web URLs to the controller methods. Visiting /upload in your browser will show the upload form, and submitting the form will send the selected images to /upload-images for processing and storage.
Step # 8 : Test the Multiple Image Upload Feature.
Now it’s time to see your image upload system in action. Start the Laravel development server by running.
php artisan server
Once the server is running, open your browser and navigate to: http://127.0.0.1:8000/upload. You should see the multiple image upload form. Select one or more images and submit the form. If everything is configured correctly, the images will be uploaded to the public/image directory and their filenames stored in the database. A success message will confirm that the upload was completed successfully.
Conclusion
By following this step-by-step guide, you’ve successfully built a multiple image upload feature in Laravel 9. From creating the project to defining the database structure, building the controller logic, designing a user-friendly upload form, and setting up routes, you now have a complete system for handling multiple image uploads. The uploaded images are stored in the public/image folder and their details saved in the database, making it easy to manage and access them whenever needed.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments