yumna12-coder's avatar

Validation upload image

how to validate image ? public function addproduct(AddProductRequest $request){

$imagepath=null; if($request->hasfile('image')){ $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,


 ]);

return redirect()->back()->with('success', 'Product added successfully!');

}

public function rules(): array
{
    return [


     'name'=>'required|string',
     'price' => 'required|numeric|min:0|max:999999.99',
     'description'=>'string',
     'Is_trend'=>'boolean',
     'category_name'=>'exists:categories,name',
     'image'=>'nullable|image|mimes:jpg,png,gif|'
        //
    ];
}
0 likes
1 reply
LaryAI's avatar
Level 58

To properly handle image uploads and validation in Laravel, there are a couple of things to adjust in your code.

Key Points:

  1. How to Retrieve and Store the Image:
    You should use $request->file('image') (not $request->validated('image')->file('image')) to get the uploaded file.
  2. Validation:
    Your validation rule for 'image' looks good, except you might want to add a max rule for file size.
  3. Fillable Fields:
    Make sure image is fillable in your Product model.

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 under storage/app/public/photos, accessible with a symlink from public/storage.

Let me know if you have any further questions!

Please or to participate in this conversation.