Модельные методы мутатора не стреляют - PullRequest
0 голосов
/ 22 мая 2019

У меня есть приложение laravel, которое использует рюкзак. В моей пользовательской форме у меня есть два поля изображения, изображение должно быть загружено в папку и имя сохранено в базе данных. Однако мутатор, который я добавил в пользовательскую модель, похоже, не срабатывает совсем.

Вновь созданный пользователь сохраняется в базе данных, но два поля длинного текста (используются для имени изображения) сохраняются как нулевые.

У меня такой же механизм на другой модели, и здесь он работает нормально. Я попытался проверить, не связаны ли имена полей и правильно ли объявлен диск, но все выглядит хорошо

Здесь я объявляю поля в пользовательском контроллере:

$this->crud->AddField([ // image
     'name' => "imglogo",
     'label' => "Logo",
     'type' => 'image',
     'upload' => true,
     'disk' => 'public'
],'imglogo');
$this->crud->AddField([ // image
     'name' => "imgheader",
     'label' => "Carta Intestata",
     'type' => 'image',
     'upload' => true,
     'disk' => 'public'
],'imgheader');

А вот те мутаторы, которые есть у меня в модели Backpackuser:

public function setImglogoAttribute($value)
    {
      dd($value);
        $attribute_name = "imglogo";
        $disk = "uploads";
        $destination_path = "loghi";

        // 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';
            //dd($filename);
            // 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;
        }
    }

    public function setImgheaderAttribute($value)
    {
      dd($value);
        $attribute_name = "imgheader";
        $disk = "uploads";
        $destination_path = "carte_intestate";

        // 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';
            //dd($filename);
            // 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;
        }
    }

На другой модели он работает нормально, поэтому, поскольку я в основном скопировал и вставил код, он должен загрузить изображение и сохранить имя в базе данных, но мутатор не запускается вообще.

...