lanky's avatar
Level 1

Backpack 4.0 images multiple upload in the another entity

Hello. How I can create multiple file uploads for model? I have ProductCrudController and Product model. I'm created Image model and pivot table product_image for many to many relationship with column id, product_id, image_id. I added mutators to both models because, I don’t know which way is right for this

ProductCrudController added upload_multiple field:;

$this->crud->addField([ 'label' => "Images", 'type' => "upload_multiple", 'name' => 'images', 'entity' => 'images', 'attribute' => "path", 'model' => "App\Models\Image", 'pivot' => true ]);

Product model: id, name, description, amount, status_id, created_at, updated_at

public function images() { return $this->belongsToMany( Image::class, 'product_image', 'product_id', 'image_id' ); }

public function setPathAttribute($value) { $attribute_name = "path"; $disk = "public"; $destination_path = "product";

    $this->uploadMultipleFilesToDisk($value, $attribute_name, $disk, $destination_path);
}

Image model: id path model is_active created_at updated_at public function products() { return $this->belongsToMany( Product::class, 'product_image', 'image_id', 'product_id' ); }

public function setPathAttribute($value) { $attribute_name = "path"; $disk = 'local'; $destination_path = "public/uploads/product";

    if ($value==null){
        \Storage::disk($disk)->delete($this->{$attribute_name});
        $this->attributes[$attribute_name] = null;
    }

    if (starts_with($value, 'data:image'))
    {
        $image = \Image::make($value)->encode('jpg', 90);
        $filename = md5($value.time()).'.jpg';
        \Storage::disk($disk)->put($destination_path.'/'.$filename, $image->stream());
        \Storage::disk($disk)->delete($this->{$attribute_name});

       
        $public_destination_path = Str::replaceFirst('public/', '', $destination_path);
        $this->attributes[$attribute_name] = $public_destination_path.'/'.$filename;

    }
}

I need when I add or update product entity I can add\update\delete images for this entity. I will be glad to any help. Thanks.

0 likes
1 reply
mary_anne's avatar

Hello, did you fix it?

I'm running on version 4

Please or to participate in this conversation.