簡體   English   中英

Laravel 背包圖片上傳問題

[英]Laravel Backpack Image Upload Issue

我正在嘗試在 Laravel 背包中上傳圖片。 我在 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;
    ]);

這是我的 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;
    }
}

它試圖將 base64 數據保存在數據庫中,但我不想這樣做。

如果有人解決它,那將是很大的幫助。 謝謝你!

我已經嘗試過文檔中顯示的代碼並且它有效。

我認為您的問題是突變器function 名稱。 要定義 mutator,您必須在 model 中定義一個方法,例如set{attribute_name}Attribute

在您的情況下,您的變異器 function 是setImageAttribute然后它正在尋找一個名為image的屬性。

我認為如果您更改此代碼:

    public function setImageAttribute($value)
{

有了這個

    public function setLogoAttribute($value)
{

它會起作用的

你錯過了一個步驟:

就像在文檔

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM