Laravel返回response()-> json()反对仅返回数组

时间:2018-09-18 08:36:25

标签: php json laravel

documentation说:

  

json方法将自动将Content-Type标头设置为   application/json

但是如果我在api.phpweb.php中有一条路由,并在其中返回一个数组,那么该标头也会被放置。

Route::get('test', function () {
    return [
        'test' => 'test'
    ];
});

enter image description here

如果可以的话,编写额外的代码response()->json(...)是否有意义?

1 个答案:

答案 0 :(得分:1)

我认为这取决于你。每当您返回任何类似于collection和arrays的值时,Laravel都会自动将其转换为JSON(尽管我从未注意到application / json标头),并且状态码为200。

含义是,如果您不希望Laravel为您设置标题,也不想使用状态代码,请使用response()->json([...], status_code_here)