業界トップクラスの求人数を誇る転職エージェントPR

リクルートグループのコネクションを活かした非公開求人も充実、他にはない好条件の求人と出会える

0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?