Uploading images is a common feature in web applications. Laravel 12 makes it easy to handle file uploads with built-in validation, storage, and retrieval functions. In this tutorial, I will show you how to upload an image in Laravel 12 with validation and store it in the public directory.
How To Image Upload in Laravel 12
If you haven’t installed Laravel 12 yet, create a new project using:
laravel new image-upload-tutorial
Open routes/web.php and define the routes for displaying the upload form and handling the submission.
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageUploadController;
Route::get('/upload', [ImageUploadController::class, 'showForm']);
Route::post('/upload', [ImageUploadController::class, 'uploadImage']);
Run the following command to create a controller:
php artisan make:controller ImageUploadController
Now, open app/Http/Controllers/ImageUploadController.php and update it as follows:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class ImageUploadController extends Controller
{
public function showForm()
{
return view('upload');
}
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
]);
$imageName = time().'.'.$request->image->extension();
$request->image->move(public_path('uploads'), $imageName);
return back()->with('success', 'Image uploaded successfully!')->with('image', $imageName);
}
}
Create a new Blade file resources/views/upload.blade.php and add the following code:
<!DOCTYPE html>
<html>
<head>
<title>Laravel 12 Image Upload</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<h2 class="mb-4">Laravel 12 Image Upload</h2>
@if(session('success'))
<div class="alert alert-success">{{ session('success') }}</div>
<img src="{{ asset('uploads/' . session('image')) }}" width="300">
@endif
<form action="{{ url('/upload') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="mb-3">
<label class="form-label">Choose Image:</label>
<input type="file" name="image" class="form-control">
@error('image')
<div class="text-danger">{{ $message }}</div>
@enderror
</div>
<button type="submit" class="btn btn-primary">Upload</button>
</form>
</div>
</body>
</html>
Start your Laravel development server:
php artisan serve
You might also like: