簡體   English   中英

Laravel 5.1-當雄辯的關系設置中不存在任何記錄時,刀片給出錯誤

[英]Laravel 5.1 - blade gives error when no record exists in eloquent relationship setup

我正在構建一個應用程序,並且在某些表上設置了雄辯的關系。 但是,當我從數據庫中提取數據並嘗試以表單形式顯示時,如果該行不存在,則會出現錯誤:

Trying to get property of non-object (View: /home/vagrant/Code/App/public/resources/views/themes/default/admin/editContractor.blade.php)

如果該行存在於數據庫中,則頁面可以正常加載而不會出現錯誤。 重要的是要注意,這些字段是可選的,因此它們可能並不總是存在於數據庫的數據透視表中。

這行似乎是導致問題的原因:

{!! Form::text($rate->field, $user->rates()->where('rate_id', $rate->id)->first()->pivot->value) !!}

我該如何解決這個問題?

在回顯值之前,您可以檢查它是否存在

{!! Form::text($rate->field, ($user->rates()->where('rate_id', $rate->id)->first()) ? $user->rates()->where('rate_id', $rate->id)->first()->pivot->value : null) !!}

就我所關心的而言,您應該這樣做:

{!! Form::text($rate->field, ($user->rates()->where('rate_id', $rate->id)->first()) or "Your default value") !!}

但是我不建議這樣做。 而是在控制器中編寫邏輯並將該數據傳遞到此視圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM