I am using Laravel Mutator in the Category Model to upload an image when creating or updating the Category
class Category extends Model
{
protected $fillable = [ 'banner','name' ];
public function banner(): Attribute
{
return Attribute::make (
get: fn ($value) => asset('images/category/Banner/'.$value),
set: function ($value) {
if(is_file($value))
{
Log::info('count');
$fileName = 'Banner_'.rand(11111,99999).'.'.$value->getClientOriginalExtension();
$value->storeAs('images/category/Banner', $fileName );
return $fileName;
}
}
);
}
}
when creating a new Category -
Category::create([
'banner' => $request->banner,
'name' => 'test category'
]);
the Log count called 9 times ,which cause the image to be uploaded 9 times ,
but if I used the Mutator the old way like this
public function setBannerAttribute($value)
{
if(is_file($value))
{
\Log::info('count');
$fileName = 'Banner_'.rand(11111,99999).'.'.$value->getClientOriginalExtension(); // renameing image
$value->storeAs('images/category/Banner', $fileName );
$this->attributes['banner'] = $fileName;
}
}
the Log count called only one time , and the image upload only once
so why
public function banner()
is being called 9 times