简体   繁体   中英

Laravel Backpack Image Upload Issue

I m trying to upload images in Laravel Backpack. I had added field in my Controller:

    $this->crud->addfield([
        'label' => "Logo",
        'name' => "logo",
        'type' => 'image',
        'upload'=> true,
        'crop' => true, // set to true to allow cropping, false to disable
        'aspect_ratio' => 1, // ommit or set to 0 to allow any aspect ratio
        //'disk'      => 'public', // in case you need to show images from a different disk
        'prefix'    => 'uploads/college/' // in case your db value is only the file name (no path), you can use this to prepend your path to the image src (in HTML), before it's shown to the user;
    ]);

Here is my Model:

    protected $fillable = ['name','description','logo','location','establised_at'];
    // protected $hidden = [];
    // protected $dates = [];

    public function setImageAttribute($value)
{
    $attribute_name = "logo";
    $disk = "public";
    $destination_path = "/uploads";

    // if the image was erased
    if ($value==null) {
        // delete the image from disk
        \Storage::disk($disk)->delete($this->{$attribute_name});

        // set null in the database column
        $this->attributes[$attribute_name] = null;
    }

    // if a base64 was sent, store it in the db
    if (starts_with($value, 'data:image'))
    {
        // 0. Make the image
        $image = \Image::make($value)->encode('jpg', 90);
        // 1. Generate a filename.
        $filename = md5($value.time()).'.jpg';
        // 2. Store the image on disk.
        \Storage::disk($disk)->put($destination_path.'/'.$filename, $image->stream());
        // 3. Save the path to the database
        $this->attributes[$attribute_name] = $destination_path.'/'.$filename;
    }
}

It's trying to save the base64 data in database but I don't want to do so.

It would be great help if anyone solve it. Thank You!

I've tried the code shown in docs and it works.

I think your problem is the mutator function name. To define a mutator you have to define a method in your model like set{attribute_name}Attribute .

In your case, your mutator function is setImageAttribute then it is looking for an attribute called image .

I think that if you change this code:

    public function setImageAttribute($value)
{

with this

    public function setLogoAttribute($value)
{

it will work

you miss a step:

like in doc

        \Storage::disk($disk)->delete($this->{$attribute_name});
        $public_destination_path = Str::replaceFirst('public/', '', $destination_path);
        $this->attributes[$attribute_name] = $public_destination_path.'/'.$filename;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM