首页 > 解决方案 > Laravel 使用 Accessors & Mutators 上传多个文件

问题描述

我有一个为上传的图像设置文件名和路径的访问器,以及一个用于检索照片 url 的 mutator。它适用于单个文件上传,但我想不出一种方法将其转换为用户库的多个文件上传。

这是我在刀片中的输入

<input type="file" id="deal_img_input" class="form-control" name="featured_image> 

这是我的模型

const PATH_PREFIX = 'public/deals';

public function getPhotoNameAttribute()
{
    if ($this->id && $this->featured_photo_extension) {
        return "$this->id.$this->featured_photo_extension";
    }

    return null;
}

public function getPhotoPathAttribute()
{
    if ($name = $this->getPhotoNameAttribute()) {
        return self::PATH_PREFIX . "/$name";
    }

    return null;
}

public function getPhotoUrlAttribute()
{
    $path = $this->getPhotoPathAttribute();
    if (Storage::exists($path)) {
        return Storage::url($path) . '?t=' . Storage::lastModified($path);
    }

    return '/assets/app/store/img/placeholder.jpg';

}

public function setPhotoExtensionAttribute($value)
{
    $path = $this->getPhotoPathAttribute();

    if (Storage::exists($path)) {
        Storage::delete($path);
    }

    $this->attributes['photo_extension'] = $value;
}

这是我的控制器

    if ($photo_featured = $request->file('feautured_image')) {
        $deals->featured_photo_alt = 'Featured Photo';
        $deals->featured_photo_extension = $photo_featured->extension();
        $photo_featured->storeAs(Deal::PATH_PREFIX, $deals->photo_name);

    }
    $deals->save();

如果我有多个输入,我该如何修改代码?

<input type="file" class="form-control" name="gallery_image[]"> 

标签: phphtmllaravel

解决方案


您是否尝试将“多个”属性添加到您的输入?

<input type="file" class="form-control" name="gallery_image" multiple="multiple">

https://stackoverflow.com/a/1593259/9291504


推荐阅读