'Laravel 8 how to use setter method to upload an image

I was using the old Laravel setter method in the model to upload an icon image when creating a new Category

    class Category extends Model
    {
        public function setIconAttribute($value)
        { 
               $fileName = 'Icon_'. $this->name .'_'.rand(11111,99999).'.'.$value->getClientOriginalExtension();  
               $destinationPath = public_path('images/Icon');
               $value->move($destinationPath, $fileName); // uploading file to given path
               $this->attributes['icon'] = $fileName;
        } 
    }

and it was working fine , now I am upgrading to the new laravel 8.77 setter

protected  function icon(): Attribute
{
    return Attribute::make (
        get: fn ($value) => asset('images/Icon/'.$value),
        set: function ($value) {
            $fileName = 'Icon_'.rand(11111,99999).'.'.$value->getClientOriginalExtension(); // renameing image  
            $destinationPath = public_path('images/Icon');
            $value->move($destinationPath, $fileName); // uploading file to given path
            return $fileName;
        }
    );
}

and it gets me an error

The file "Finishe_30574.png" was not uploaded due to an unknown error.

so first how to fix this error

and how to add the attribute name ($this->name) in the file name - in the new Laravel-8 setter like the old way

   $fileName = 'Icon_'. $this->name .'_'.rand(11111,99999).'.'.$value->getClientOriginalExtension();  

because adding ($this->name) in the new setter way getts an error



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source