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).
This is only part of the article. For the full discussion, with examples and step-by-step details, you can read it on the original source:
How to Upload Images in Laravel with Validation
More programming tutorials and developer tools are also available at dhiecoderweb.com.
Top comments (0)