LoginSignup
2
3

More than 5 years have passed since last update.

APIを経由してオブジェクトのプロパティを取得するときの注意

Last updated at Posted at 2017-03-21

DBの参照用APIをLaravelでつくっていたときに詰まったハナシ。

api.php
Route::get('/product', function(){
    $product = ProductEloquent::find(3);
    return $product;
});

こんな感じで、Eloquentで取得したデータをオブジェクトで返すようにして、
下のようなテストを実行。

class ProductTest extends TestCase
{
    /**
     * A basic test example.
     * @group api
     * @return void
     */
    public function testBasicTest()
    {
        $res = $this->get("api/product");

        dd($res->category);
    }
}

エラー

ErrorException: Undefined property: Illuminate\Http\Response::$category

プロパティがないとのこと。
dd($res) で中を見てみると、確かにEloquentで取得したときのオブジェクトに比べて何かフクザツな構造になっていた。

解決法

これで解決。

    public function testBasicTest()
    {
        $res = $this->get("api/product");

        dd($res->baseResponse->getOriginalContent()->category);
    }
2
3
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
2
3