Home > Back-end >  unlink(): Invalid argument this error is occurred while update image in laravel
unlink(): Invalid argument this error is occurred while update image in laravel

Time:01-05

I am trying to update image to image/brand/ folder but unexpectedly error is occurred.

public function update(Request $request,$id){

        $validated = $request->validate([
            'brand_name' => 'required|max:4',
            // 'brand_image' => 'required|mimes:jpg,jpeg,png',
        ]);

        $old_image=$request->old_image;
        $brandimage=$request->file('brand_image');

        $image_gen=hexdec(uniqid());
        $image_exten=strtolower($brandimage->getClientOriginalExtension());
        $image_name=$image_gen.'.'.$image_exten;
        $image_location='image/brand/';
        $image_uplioad= $image_location.$image_name;

        $brandimage->move($image_location,$image_name);

        unlink($old_image);

        Brand::find($id)->update([
            'brand_name' =>$request->brand_name,
            'brand_image'=>$image_uplioad,
            'Created_at'=> Carbon::Now()
        ]);

        return  Redirect()->back()->with('success','Brand image updated Successfully');


    }

ErrorException
unlink(): Invalid argument this is the error what i got i need over come this problem please help

CodePudding user response:

please pass the $old_image=$request->old_image; value from in blade.

CodePudding user response:

You could optimize it by update the image from model by creating updateImage method inside the model like this

Brand Model

.....
    public function updateImage($image)
    {
        $oldImage = $this->brand_image?? '';
      
        $this->brand_image = $image->store('brand', 'public');

        $this->save();

        Storage::disk('public')->delete($oldImage);
    }
.....

after that the controller will be like this

  $validated = $request->validate([
        'brand_name' => 'required|max:4',
        // 'brand_image' => 'required|mimes:jpg,jpeg,png',
    ]);

    $brand = Brand::find($id)->update([
        'brand_name' =>$request->brand_name,
        'Created_at'=> Carbon::Now()
    ]);

    if($request->hasFile('brand_image'))
        $brand->updateImage($request->file('brand_image'));

    return  Redirect()->back()->with('success','Brand image updated Successfully');
  • Related