我在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