Kavyajain's avatar

Multiple file upload laravel backpack

Hello Folks, follow the below code if you want to add multiple upload to your project with laravel backpack. Also, you need not create any edit and create form as the below code does it for you.

Include this in controller

$this->crud->addColumn([
            'name' => 'image',
            'label' => 'Banner Image',
            'type' => 'array',
        ]);

        $this->crud->addField([   
            'name' => 'image',
            'label' => 'Banner Image',
            'type' => 'upload_multiple',
            'upload' => true,
        ], 'both');

In model

 protected $casts = ['image' => 'array'];

public function uploadMultipleFilesToDisk($value, $attribute_name, $disk, $destination_path)
    {
        $request = \Request::instance();
        $attribute_value = (array) $this->{$attribute_name};
        $files_to_clear = $request->get('clear_'.$attribute_name);
        // if a file has been marked for removal,
        // delete it from the disk and from the db
        if ($files_to_clear) {
            $attribute_value = (array) $this->{$attribute_name};
            foreach ($files_to_clear as $key => $filename) {
                \Storage::disk($disk)->delete($filename);
                $attribute_value = array_where($attribute_value, function ($value, $key) use ($filename) {
                    return $value != $filename;
                });
            }
        }
        // if a new file is uploaded, store it on disk and its filename in the database
        if ($request->hasFile($attribute_name)) {
            foreach ($request->file($attribute_name) as $file) {
                if ($file->isValid()) {
                    // 1. Generate a new file name
                    $new_file_name = $file->getClientOriginalName();
                    // 2. Move the new file to the correct path
                    $file_path = $file->storeAs($destination_path, $new_file_name, $disk);
                    // 3. Add the public path to the database
                    $attribute_value[] = $file_path;
                }
            }
        }
        $this->attributes[$attribute_name] = json_encode($attribute_value);
    }


public function setImageAttribute($value)
    {
        $attribute_name = "image";
        $disk = "uploads";
        $destination_path = "Images";

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

And you are done. Thank You

0 likes
0 replies

Please or to participate in this conversation.