response()->json() と return [a, b, c]のちがい


Too Long; Don't Read

LaravelでのAPIレスポンスの書き方において、  
以下の2つが同じ意味だと思っていた。


return response()->json(
    $response['error_message'],
    $response['status_code'],
    $response['example_text']
);

return [ 
    $response['error_message'],
    $response['status_code'],
    $response['example_text'] 
];

json()の省略形が[]かな くらいに思っていた。

それぞれの結果は以下。


return response()->json(
    $response['error_message'],
    $response['status_code'],
    $response['example_text']
);

// Type error: Argument 3 passed to Illuminate\Routing\ResponseFactory::json() must be of the type array, string given, called in ~~~~

return [ 
    $response['error_message'],
    $response['status_code'],
    $response['example_text'] 
];

// { 'error_message', 500, 'example text' }

前者はエラーが起こっているのに対し、
後者は渡した内容をjson型にしている。

題目のresponse()->json() と return [a, b, c]のちがい
とは、この点になる。

後述するが、json()の引数はそれぞれ格納するものが決まっていて、第二引数以降にオプションを指定することができる。

そのため、
ただjson型のデータを渡せば良い時と、
オプションを指定して受け取り手へ明示的に値を渡したい時とで、使い分けると良い。

今回の場合は
ajaxのdone(), fail() への振り分けを行いたかったことから、
第2引数でHttpステータスを明示できるjson()の書き方を用い、
以下の書き方に変更して無事解決。

return response()->json(
    $response, 
    $response['status']
);

勘違いの要因

return response()->json( ['a', 'b', 'c'] );

配列でjson()に渡すパターンとjson関数の仕様をごっちゃに覚えていたから。

json( )の仕様

json()はjson_encode()を内部で用いている。

json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] ) : string

value
エンコードする値。 リソース 型以外の任意の型を指定できます。
options
JSON_FORCE_OBJECT, .....からなるビットマスク。

以降Arrayで渡す

depth
最大の深さを設定します。正の数でなければいけません。

引数にはそれぞれ受け付ける型と意味が決まっているため、
Arrayで渡すべきところにStringを渡して、型エラーが出ていたのでした。

感想

調べているうちにAjaxのdone, fail の振り分けについても詳しくなれたので良かった。