Laravel Backpack 上传图片自动保存至七牛

更新日期: 2017-09-18 阅读次数: 6842 分类: Laravel

默认 Backpack 上传的图片是保存到本地,但是现实场景中都是用 CDN 存储图片,以提升用户体验。所以就需要改造上传的流程,这里用到了 Laravel 七牛的接口实现。

根据 Backpack 文档的说明,需要在 mutator 中进行改造。

参考 Laravel 文档,https://laravel.com/docs/5.3/eloquent-mutators#defining-a-mutator

Mutator 名词,增变基因

To define a mutator, define a setFooAttribute method on your model where Foo is the "studly" cased name of the column you wish to access. So, again, let's define a mutator for the first_name attribute. This mutator will be automatically called when we attempt to set the value of the first_name attribute on the model

例如

public function setFirstNameAttribute($value)
{
        $this->attributes['first_name'] = strtolower($value);
}

所以,需要改造的地方就是这里,在这里将上传的文件保存至七牛云,并将七牛云中该图片的名字存储到数据库中 (这也是为啥要使用 mutator 的原因)

用怎样的名字呢?

  • 原始文件名。不行。因为客户端本地文件名可能会重复。
  • UUID。这个可行。

最终代码

public function setImageAttribute($value) {
	$disk = QiniuStorage::disk('qiniu');

        // set image name
        $filename = uniqid(env('QINIU_BUCKET').'_');
        $this->attributes['image'] = $filename;

        // save to qiniu
	$disk->put($filename, file_get_contents($value->getRealPath()));
}

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式