Assuming Laravel 9 follows similar conventions as previous versions, here’s how you might achieve multiple image uploads with validation:
Setup Routes:
First, define the routes in your routes/web.php
file to handle the upload form and the submission.
use App\Http\Controllers\ImageUploadController; Route::get('/image-upload', [ImageUploadController::class, 'showUploadForm']); Route::post('/image-upload', [ImageUploadController::class, 'uploadImages']);
Create Controller: Next, create a controller to handle the image uploads. You can generate a controller using the Artisan command:
php artisan make:controller ImageUploadController
In the ‘ImageUploadController.php‘ file, you’ll have methods like showing ‘UploadForm‘ to display the upload form and uploadImages to handle the submission.
namespace App\Http\Controllers; use Illuminate\Http\Request; class ImageUploadController extends Controller { public function showUploadForm() { return view('image-upload'); } public function uploadImages(Request $request) { $request->validate([ 'images' => 'required|array', 'images.*' => 'image|mimes:jpeg,png,jpg,gif|max:2048', ]); if ($request->hasFile('images')) { foreach ($request->file('images') as $image) { $imageName = time() . '-' . $image->getClientOriginalName(); $image->storeAs('uploads', $imageName); } return redirect()->back()->with('success', 'Images uploaded successfully.'); } return redirect()->back()->with('error', 'No images were uploaded.'); } }
Create View:
Create a Blade view named ‘image-upload.blade.php’ to display the upload form.
<!DOCTYPE html> <html> <head> <title>Multiple Image Upload</title> </head> <body> @if(session('success')) <div>{{ session('success') }}</div> @endif @if(session('error')) <div>{{ session('error') }}</div> @endif <form action="/image-upload" method="POST" enctype="multipart/form-data"> @csrf <input type="file" name="images[]" multiple> <button type="submit">Upload</button> </form> </body> </html>
Article Categories:
Laravel