glukash's avatar

response json and Content-Type

Can you tell me why this piece fo code, placed in controller:

$model = \App\Model::first();
return response()->json($model->toArray());

gives a wrong header: Content-Type: text/html; charset=UTF-8

while this code:

$model = \App\Model::first();
header('Content-Type: application/json; charset=utf-8');
echo json_encode($model->toArray());
exit;

gives a proper header: Content-Type: application/json; charset=utf-8

0 likes
2 replies
Ricus's avatar

Try returning

Response::JSON(array('foo'=>'bar'));
constb's avatar

@glukash

return $model->toArray();

or even

return $model;

when your returning from action method something that is not a string or a view, it gets json_encoded automatically. I'm not sure, but I think it sets headers too.

Please or to participate in this conversation.