Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel 4 why send content-type when sending json?

Tags:

php

laravel

In the book of laravel I read, and also my co-worker who has experience with laravel said that generating JSON I should in laravel way.

Why do I need to do this:

Route::get('markdown/response', function()
{
    $data = array('iron', 'man', 'rocks');
    return Response::json($data);
});

As I read it sends also content-type header when using this.

When I was using codeigniter I used to do simply this:

echo json_endode($data);

and never ever ever had any problems. Even if it is not set content type. Actually I dont know maybe php sets it automatically, but since I did not have problems, I did not care.

And when using 'new' technology I really want to know why it is better than good old one.

like image 688
Dariux Avatar asked Jan 25 '26 01:01

Dariux


2 Answers

With respect, by not providing a content-type header, you were doing it "wrong" when coding in CodeIgniter.

Most clients (browsers, ajax requests, especially jQuery) can still can guess how to handle the response correctly and so probably "just worked" for you. You were likely always implicitly returning a Content-Type: text/html with your response, which is a default header in CodeIgniter.

You should always return a proper content type with your HTTP responses so the consuming client knows how to treat this content. Note that this is a mechanism of HTTP as defined in specification, not specific to any framework or even a language.

Response::json()

The above code is just a convenience function, where Laravel will automatically set the application/json header for you, as well as convert an array of data into JSON format. The only effective difference from your CodeIgniter code is the setting of the header, as you've pointed out.

It's worth noting that the Response object extends Symfony's response object, which is very "powerful" - in other words, it's a very good implementation of the HTTP protocol.

like image 115
fideloper Avatar answered Jan 27 '26 16:01

fideloper


The response object returned from Response::json (and other Response static methods) are highly modifiable.

$response = Response::json($data);
$response->header('Content-Type', 'application/json');
return $response;

You can check for more available methods in the Laravel and Symfony code API.

http://laravel.com/api/class-Illuminate.Http.Response.html http://api.symfony.com/2.1/Symfony/Component/HttpFoundation/Response.html

like image 30
Andreas Avatar answered Jan 27 '26 16:01

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!