9
4

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.

Trying to get property 'id' of non-object () 解決方法

Posted at

Laravel入門(p.208)で、クエリビルダを使って指定したIDのレコードを取得し、ブラウザ表示させようとした時に次のエラーが発生しました。

Trying to get property 'id' of non-object (View: /work/resources/views/hello/show.blade.php)

スクリーンショット 2021-03-07 22.42.53.png

このエラーは、存在しないプロパティを取得しようとすると発生します。
結論から言ってしまうと、このエラーの原因は、/hello/showにアクセスする際に、
ただ?id=1のようにパラメータを用意していなかったからでした(笑)
ただの参考書の見逃しでした。

しかし、エラーについて調べていると、どうやらリレーションの先が無かった場合にnullを返してくれる関数があるらしく、
その関数を使うことで今回のエラーを解決できるようなので試しに使ってみました。

optional( )

その関数がこちらです!
この関数はヘルパー関数といい、渡されたオブジェクトに対し、is_objectが真の場合はオブジェクトとプロパティを渡し、nullの場合は例外を回避してくれます。

ということで早速下記のようにテーブル表示の記述を修正して/hello/showにアクセスしてみます。

「show.blade.php」

@section('content')
    <table>
        <tr><th>id: </th><td>{{$item->id}}</td></tr>
        <tr><th>name: </th><td>{{$item->name}}</td></tr>
        <tr><th>mail: </th><td>{{$item->mail}}</td></tr>
        <tr><th>age: </th><td>{{$item->age}}</td></tr>
    </table>
    </item>
@endsection

↓ //optional関数追加

@section('content')
    <table>
        <tr><th>id: </th><td>{{optional($item)->id}}</td></tr>
        <tr><th>name: </th><td>{{optional($item)->name}}</td></tr>
        <tr><th>mail: </th><td>{{optional($item)->mail}}</td></tr>
        <tr><th>age: </th><td>{{optional($item)->age}}</td></tr>
    </table>
    </item>
@endsection

これで、再度パラメータを用意せずに/hello/showにアクセスしてみます。

スクリーンショット 2021-03-07 23.01.43.png

すると、ご覧の通りレコードが無くてもnullの状態でテーブル表示されました。

では、次はちゃんとパラメータを用意して/hello/show?id=2でアクセスしてみます。
スクリーンショット 2021-03-07 23.04.36.png

すると、idが2のレコードがちゃんと表示されました!

参考サイトはこちら
https://qol-kk.com/wp2/blog/2018/12/19/post-992/
https://neco.sakuratan.com/laravel-20190909/

9
4
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
9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?