4
3

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 5 years have passed since last update.

LaravelでDBからstdClassで取得したオブジェクトにプロパティが含まれているか調べる方法

Last updated at Posted at 2018-07-19

問題点

例えば以下のような文があったとします。

example.php
$result = DB::table('test_table')
                   ->select('hoge', 'fuga', 'piyo')
                   ->where('id', 123456)
                   ->get();

これで取得できる値はhoge, fuga, piyoのカラムの値が取得できるはずなのですが、
過去のDBのカラム追加などで値が含まれていないレコードが取得される場合があり、
その場合矢印演算子でプロパティにアクセスすると例外を吐いて落ちてしまいます。

ですのでproperty_existsなどで存在の有無を調べる必要があるのですが、Laravelで取得されるオブジェクト配列はstdClassで動的に作成されているためproperty_existsでは調べることができませんでした。

解決法

example.php
$result = DB::table('test_table')
                   ->select('hoge', 'fuga', 'piyo')
                   ->where('id', 123456)
                   ->get();

$properties = get_object_vars($result[0]);
echo (array_key_exists('piyo', $properties) ? $result[0]->piyo : "no data");

その他

根本的にstdClassでの取得を止められるなら設定変えてしまうのも手段の一つです。

Laravelで、DBやEloquentクラスでsqlを実行してget()したけど、結果がstdClassになっちゃった場合 - It's now or never. @chocopie116

参考

php - Property exists but property_exists() return false; - Stack Overflow
php stdClass check for property exist - Stack Overflow

4
3
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?