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

发布时间: 2017-09-18 11:33:07 作者: 大象笔记

默认 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 的原因)

用怎样的名字呢?

最终代码

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()));
}
我是一名山东烟台的开发者,联系作者