首页 > 解决方案 > Laravel 背包图片上传问题

问题描述

我正在尝试在 Laravel Backpack 中上传图片。我在控制器中添加了字段:

    $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;
    ]);

这是我的模型:

    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;
    }
}

它试图将 base64 数据保存在数据库中,但我不想这样做。

如果有人解决它,那将是很大的帮助。谢谢你!

标签: laravellaravel-backpackintervention

解决方案


我已经尝试过文档中显示的代码并且它有效。

我认为您的问题是突变函数名称。要定义一个 mutator,你必须在你的模型中定义一个方法,比如set{attribute_name}Attribute.

在您的情况下,您的 mutator 函数setImageAttribute正在寻找一个名为image.

我认为如果您更改此代码:

    public function setImageAttribute($value)
{

有了这个

    public function setLogoAttribute($value)
{

它会起作用的


推荐阅读