我在Laravel(第一个项目)非常环保,所以如果我犯了新手错误,请耐心等待。我试图通过Laracasts运行时创建这个项目,所以我使用他的建议。我正在使用Laravel 5.4和PHP 7.1.4Laravel 5如何在验证前运行mutator
我在布尔字段的窗体上有一个复选框。如果在提交表单时没有选中复选框,则返回null。我不希望布尔值为空值,所以我有一个验证器,确保它只接受真/假值。为了这个工作,我必须创建一个mutator,如果它为null,则将其值更改为false。
我有两个模型,Item和ItemNote。我试图从Item模型创建ItemNote。在Item页面上,有一个地方可以添加运行到ItemNoteController的ItemNote,然后调用Item中的方法来添加ItemNote。问题是我无法让修改器在ItemNote模型中运行,因此验证失败,因为布尔字段(calendar_item)为空。
我是第一次尝试从与Item的关系创建ItemNote,根据这个堆栈溢出Laravel 5 mutators only work when I create a record and not when I update a record答案当通过关系创建时,mutator不会运行$ this-> notes() - > create($ request->所有())。您必须使用模型$ this-> notes-> create($ request-> all())注意注释后缺少括号。所以我尝试了所有我可能想到的尝试通过模型创建对象,并且仍然无法让mutator运行。
这里有关系的声明在我的模型:
项目
public function notes() { return $this->hasMany(ItemNote::class); }
ItemNote
public function item() { return $this->belongsTo(Item::class); }
赋值函数在ItemNote为calendar_item
protected function setCalendarItemAttribute($value) { $this->attributes['calendar_item'] = isset($value) ? $value : FALSE; }
在V在ItemNote alidation规则
public static $validationRules = array('note_date' => 'required|date',
'resolve_date' => 'nullable|date',
'notes' => 'required|string',
'cost' => 'nullable|numeric',
'calendar_item' => 'required|boolean',
'attachment_path' => 'nullable|string|max:200');
这是ItemNoteController从商品页面中
public function store(Item $item)
{
$this->validate(request(), ItemNote::$validationRules);
$item->addNote(new ItemNote(request(['item_note_category_id', 'note_date', 'resolve_date',
'notes', 'cost', 'calendar_item', 'attachment_path'])));
return back();
}
这里添加ItemNote时运行的动作是在项目模型
public function addNote(ItemNote $note)
{
$this->item_note->save($note);
}
功能addNote以下是我在addNote中尝试过的不同的东西,它们都无法运行mutator。创建语句列出了字段分配,但为了简洁起见,我在此将其删除。
$this->notes->save($note);
$this->notes()->save($note);
$this->item_note->save($note);
$this->notes->create
$this->item_notes->create
$this->item_notes()->create
$this->item_note->create
$this->item_note()->create
$this->ItemNote->create
$this->ItemNote()->create
ItemNote::create
以上所有的工作,但我认为这 - $> item_notes->创建,因为在所有的关系,名字是笔记不应该工作,但它不会抱怨这让我觉得这可能不是得到这个代码,并且它在控制器中的验证语句上失败。如何在验证之前运行mutators?还是有更好的方法来在验证之前清理数据?
我也尝试把item_id字段放在验证规则中,但总是失败,因为item_id没有被分配,直到我通过关系创建对象。我想要求它,但还没有想出如何让它在请求中分配。
任何帮助表示赞赏。对不起,很长的文章。
不知道what't错,但这个语法是正确的函数:$ this->笔记() - >保存($注); –
dd($ item-> addNote(new ItemNote(request(...)))); –
我把dd($ item-> addNote(new ItemNote(request(['item_note_category_id','note_date','resolve_date', 'notes','cost','calendar_item','attachment_path'])))) ;在validate语句之前,我得到FatalThrowableError调用成员函数save()null。也许我应该在验证之后把它放在别的地方? – PhishTail