Laravel では配列をそのまま返却すると JSON が返る

2015/01/29

P1110954.JPG

タイトルですべてを言うたったけど、以下説明。

Laravel で JSON 返却するときは、

return Response::json(array('name' => 'Steve', 'state' => 'CA'));

とかいう感じで書くんですが、今朝は寒かったので、手が滑って、

return array('name' => 'Steve', 'state' => 'CA');

こう書いてしまった。でも、JSON が返ってくる。「なんで???」ってなったと。

で、調べてみたら、

https://github.com/laravel/framework/blob/4.2/src/Illuminate/Http/Response.php#L31

ココらへんに、

        // If the content is "JSONable" we will set the appropriate header and convert
        // the content to JSON. This is useful when returning something like models
        // from routes that will be automatically transformed to their JSON form.
        if ($this->shouldBeJson($content))
        {
            $this->headers->set('Content-Type', 'application/json');

            $content = $this->morphToJson($content);
        }

って書いてあって、shouldBeJson() を見てみたら、

        	protected function shouldBeJson($content)
	{
		return $content instanceof JsonableInterface ||
			   $content instanceof ArrayObject ||
			   is_array($content);
	}

ってなってたというおはなしでした。

ところで、最近、クラフトビールと Laravel にはまってます。どちらも大好きです。

では、また。