kendrick's avatar

Product Creation / Post Method incl. Picture?

Hello everybody, how are you?

So I am currently working on a Product setup for my Users. Therefore I would like to let them edit the product within one view, and upload content such as Title, Description and Price plus a Picture (or several pictures).

I've created an ProductUploadController:

public function postProductEdit(Request $request){
        
        $this->validate($request, [

            'title'=> 'max:140',
            'description'=> 'max:140',
            'price'=> 'max:140',
            'product_image'=> 'max:3000',

            
        ]);

        
        $update = Auth::user()->products()->create([
            'business_id' => auth()->user()->id,
            'title' => $request->title,
            'description' => $request->description,
            'price' => $request->price,
            'product_image' => $request->product_image,
            
        ]);

        if($request->hasFile('product_image')){

            $business = Auth::user();
            $image   = $request->file('product_image');         
            $filename = time() . '.' . $image->getClientOriginalExtension();            
            $location = public_path('uploads/business/products/'. $filename );          
            Image::make($image)->resize(812, null, function ($constraint){$constraint->aspectRatio();})->save($location);
            
            $business->product_image = $filename;
            $business->save();  
        


        return redirect()
            ->route('products.edit')
            ->with('info', 'Your product has been updated.');
}

So how am I able to integrate the Storeimage function within my Post Method correctly. By now it won't work with my Controller from the top.

Any suggestions? Thank you.

0 likes
1 reply
Snapey's avatar

your route should include the id of the product you are editing.

Then find that product and fill() it with the new values, followed by save()

for images stored against models I can recommend the spatie media library package

Please or to participate in this conversation.