如何在存储到数据库之前自定义模型的字段


How to customize a field of the model before storing in database

我有一个这样的模型:

class Article extends Model {
protected $fillable = [
    'title',
    'body',
    'img_profile', // store name of image
    ];
}

和这样的控制器:

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,但我只想在img_profile中更新file_name

如何在将img_profile请求存储在数据库之前更改其值?

您应该这样使用Article模型的mutator:

public function setImgProfileAttribute($value)
{
    $this->attributes['img_profile'] = '/private/var/tmp/phpceBMP2/'. $value;
}

但是,您应该考虑是否真的想以这种方式在DB中存储路径。如果你将来想要更改它怎么办?你要更新所有的记录吗?