我的规则和可填充数组在
之下protected $fillable = [
'title', 'cover', 'price', 'dumping', 'description'
];
protected $rules = [
'title' => 'required|max:255|unique:packages',
'price' => 'required|numeric|between:0.01,999999.99',
'dumping' => 'sometimes|nullable|numeric|between:0.01,999999.99'
];
正如你在上面看到的那样,我在fillable中没有名为slug的属性,因此用户无法按需填写此列
public static function boot()
{
parent::boot();
if ( $model->id ){
$this->rules['slug'] .= ',slug,'.$model->id;
}
static::saving(function($model){
$model->slug = str_slug($model->title);
});
}
但
如果我想更新模型,我必须通过标题
验证slug属性的使用str_slug($模型 - >标题)
我不知道我该怎么做?
我怎么能这个动态规则?
(抱歉我的英语不好)
答案 0 :(得分:0)
$data = array_merge($request->except('slug'), ['slug' => $request->has('title') ? str_slug($request->title) : '' ]);
$package = new Package();
if ( $package->validate($data) ){
$package->fill($request->all())->save();
\Session::flash('success', __('common.message.success.add'));
return redirect()->route('admin.package.list');
}
protected $rules = [
'title' => 'required|max:255|unique:packages',
'slug' => 'required|max:255|unique:packages',
'price' => 'required|numeric|between:0.01,999999.99',
'dumping' => 'sometimes|nullable|numeric|between:0.01,999999.99'
];
public static function boot()
{
parent::boot();
static::saving(function($model){
$model->slug = str_slug($model->title);
});
}
这样,除了使用标题
之外,我保护slug不受其他对象的影响度过愉快的一天...... :)