0
0

More than 3 years have passed since last update.

【Laravel】Trying to get property '〇〇' of non-object(View: /〜/views/menu/index.blade.php) の解決方法

Posted at

エラー概要

このエラーは、〇〇に値が入っていないのに、プロパティを参照しようとしてるよっていうエラーです。

エラー発生時のコード

menu/index.blade.php
@foreach ($items as $item)
    <tr>
        <td>{{$item->time}}</td>
        <td>{{$item->user->name}}</td>
    </tr>
@endforeach
MenuController.php
public function index(Request $request)
{
    $items = Menu::with('user')->get();
    return view('menu.index',['items' => $items]);
}

解決方法

値がなくてもnullを返してくれるようにヘルパー関数optional()を使います。

menu/index.blade.php
@foreach ($items as $item)
    <tr>
        <td>{{$item->time}}</td>   
        <td>{{optional($item->user)->name}}</td>
    </tr>
@endforeach

参考文献

おわりに

結構苦戦したけど、案外簡単な方法でした。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0