Upload & Store Images in Laravel with Validation and Storage

Handling image uploads is a common requirement in web development. Laravel makes this task simple and elegant with its built-in validation and file storage system. In this tutorial, we'll walk through how to upload and store images in Laravel the right way.
1. Setting Up the Form
Let's create a simple form to allow image uploads.
<form action="{{ route('image.upload') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
Note: Make sure to set
enctype="multipart/form-data"
in your form.
2. Creating the Route
Add a route to handle the form submission:
use App\Http\Controllers\ImageController;
Route::post('/upload-image', [ImageController::class, 'store'])->name('image.upload');
3. Creating the Controller
Generate a controller:
php artisan make:controller ImageController
Inside ImageController
, add the store
method:
use Illuminate\Http\Request;
public function store(Request $request)
{
// Validate the image
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'
]);
// Store the image
$path = $request->file('image')->store('images', 'public');
// You can now save $path to database if needed
return back()->with('success', 'Image uploaded successfully!')->with('path', $path);
}
Validation Rules Explained:
required
— ensures the file is uploadedimage
— restricts to image file typesmimes
— allows specific extensionsmax
— sets file size limit (in KB)
4. Configuring Storage
Ensure the public
disk is set in your config/filesystems.php
:
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL') . '/storage',
'visibility' => 'public',
],
Then run the following to link storage to the public folder:
php artisan storage:link
This will create a symbolic link from public/storage
to storage/app/public
.
5. Displaying the Uploaded Image
You can now display the uploaded image using:
@if(session('path'))
<img src="{{ asset('storage/' . session('path')) }}" alt="Uploaded Image" width="300">
@endif
Best Practices
- Always validate file types and sizes
- Store file paths in the database for reference
- Rename uploaded files if needed (to avoid name conflicts)
- Consider organizing uploads by user or date
Conclusion
Laravel provides a clean and robust way to handle image uploads. With validation, storage, and a few lines of code, you can implement a secure image upload system.
Need help with multiple image uploads or image resizing? Let me know and we’ll expand this guide!