我有一个这样的模型:
class Article extends Model {
protected $fillable = [
'title',
'body',
'img_profile', // store name of image
];
}
还有一个像这样的 Controller :
public function store(ArticleRequest $request){
$article = Auth::user()->articles()->create($request->all());
return redirect('articles');
}
还有这样的表格:
{!! Form::model($article = new \App\Article,['url' => 'articles','files' => true ]) !!}
{!! Form::text('title', null ) !!}
{!! Form::textarea('body', null) !!}
{!! Form::file ('img_profile', '') !!}
{!! Form::submit('Submit') !!}
{!! Form::close() !!}
当我提交表单时,img_profile
字段存储默认缓存文件,即 /private/var/tmp/phpceBMP2
.但我只想更新file_name
在img_profile
.
如何更改 img_profile
的值在将其存储到数据库之前请求?
最佳答案
您应该使用mutator对于 Article
模型如下:
public function setImgProfileAttribute($value)
{
$this->attributes['img_profile'] = '/private/var/tmp/phpceBMP2/'. $value;
}
但是您应该考虑是否真的想以这种方式将路径存储在数据库中。如果您将来想更改它怎么办?您必须更新所有记录吗?
关于php - 如何在存储到数据库之前自定义模型的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31322518/