LoginSignup
0
0

More than 3 years have passed since last update.

[Laravel]DBより抽出したデータをクエリビルダでとれなかったときの話

Posted at

エラー文

Property [id] does not exist on this collection instance.

このコレクションインスタンスにはidプロパティはありませんとのこと。

該当ソース

$data = DB::table('users')->where('id',1)->get();

これをview側で$data->idとしたときに上記エラーが起こった。
->get()の返り値はCollectionクラス。
Collectionの中身はModelの各データで構成されている。data->idで取るデータはModelの中のプロパティ変数を取るものなので、データが1件しかなくとも、各Modelの集合体の配列であるCollectionからは$data->idという取り方ではエラーが出た。

解決方法

$data = DB::table('students')->where('id',1)->first();

->first()の返り値はmodelオブジェクト

まとめ

view側で$data->idというように単純に一件だけデータを取りたいときは、->first()や->find()などで、Modelのオブジェクトを返すようにする必要がある。

参考文献

【Laravel】Property [id] does not exist on this collection instance.

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