Image upload is a feature found in almost every web application — profile photos, article thumbnails, products, and more. Laravel provides a clean and secure way to handle it. This article covers image upload from the form to displaying it, complete with validation.
Step 1: Prepare the Upload Form
The upload form must use enctype="multipart/form-data":
<form action="/upload" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
Step 2: Validate the File in the Controller
Always validate the file type and size for security — never trust user input:
public function store(Request $request)
{
$request->validate([
'image' => 'required|image|mimes:jpg,jpeg,png,webp|max:2048', // max 2MB
]);
// store in storage/app/public/uploads
$path = $request->file('image')->store('uploads', 'public');
// save $path to the database if needed
return back()->with('success', 'Image uploaded successfully!');
}
The image rule ensures the file is really an image, mimes restricts the formats, and max:2048 limits the size (in kilobytes).
Step 3: Create the Storage Symbolic Link
So that files in storage/app/public can be accessed publicly, run once:
php artisan storage:link
This command creates a shortcut from public/storage to storage/app/public.
Step 4: Displaying the Image
Use the asset() helper with the storage/ prefix:
<img src="{{ asset('storage/' . $path) }}" alt="Image">
Step 5: Naming the File Yourself (Optional)
If you want a unique and tidy file name, for example based on the time:
$file = $request->file('image');
$fileName = 'img_' . uniqid() . '.' . $file->getClientOriginalExtension();
$path = $file->storeAs('uploads', $fileName, 'public');
Step 6: Deleting the Old Image
When replacing or deleting a record, also delete the file so storage doesn't pile up:
use Illuminate\Support\Facades\Storage;
Storage::disk('public')->delete($path);
Security Tips
- Always restrict the
mimesandmaxfile size. - Don't store uploaded files directly in the
publicfolder without validation. - For large images, consider resizing them to save storage and speed up loading.
Conclusion
Image upload in Laravel is safe and easy as long as you validate the type & size, save via store(), and run storage:link. With the pattern above, you can handle profile photos, thumbnails, or product galleries neatly. To speed up image loading on your site, also see our guide on Laravel performance optimization.