Level 58
To properly handle image uploads and validation in Laravel, there are a couple of things to adjust in your code.
Key Points:
- How to Retrieve and Store the Image:
You should use$request->file('image')(not$request->validated('image')->file('image')) to get the uploaded file. - Validation:
Your validation rule for'image'looks good, except you might want to add amaxrule for file size. - Fillable Fields:
Make sureimageis fillable in yourProductmodel.
Improved Controller Method
Here’s how your addproduct method should look:
public function addproduct(AddProductRequest $request)
{
$imagepath = null;
if ($request->hasFile('image')) {
// Store image and get its path
$imagepath = $request->file('image')->store('photos', 'public');
}
$product = Product::create([
'name' => $request->validated('name'),
'price' => $request->validated('price'),
'description' => $request->validated('description'),
'Is_trend' => $request->validated('Is_trend'),
'image' => $imagepath,
// Add category_name if it is used in your model
]);
return redirect()->back()->with('success', 'Product added successfully!');
}
Improved Validation Rules
If you want to restrict the image size to 2MB, for example:
public function rules(): array
{
return [
'name' => 'required|string',
'price' => 'required|numeric|min:0|max:999999.99',
'description' => 'string|nullable',
'Is_trend' => 'boolean|nullable',
'category_name' => 'exists:categories,name',
'image' => 'nullable|image|mimes:jpg,png,gif|max:2048', // 2MB max
];
}
Summary
- Always use
$request->file('image')to get the file instance for storage. - Storing files with
store('photos', 'public')puts them understorage/app/public/photos, accessible with a symlink frompublic/storage.
Let me know if you have any further questions!