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

标签 php laravel eloquent laravel-5 mutators

我有一个这样的模型:

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_nameimg_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/

相关文章:

php - Laravel - 有没有办法结合 whereHas 和 with

javascript - 无法在php中调用脚本标签

php - 搜索框无法显示结果,即使关键字与php中的数据库匹配,搜索框也始终不显示结果

php - 错误: wrong mysql library version or lib not found (when building PHP 7 with a custom built MySQL 8)

php - 更改公用文件夹名称后使用 artisan serve

php - 在 laravel eloquent 中一起使用 with 和 withCount

使用 JWT Auth 时 Laravel 5.3 节流登录

Laravel - timestamp() 和 timestampTz() 有什么区别?

php - Laravel 8 Eloquent : How to set OR condition to where clause in Laravel

php - Eloquent其中连接多个表