Well, let’s look at the source code of both?
Wantsjson:
public function wantsJson()
{
$acceptable = $this->getAcceptableContentTypes();
return isset($acceptable[0]) && $acceptable[0] == 'application/json';
}
Ajax:
public function ajax()
{
return $this->isXmlHttpRequest();
}
The method wantsJson
checks if the header accept
holds the value application/json
. This means that the application is saying, through the header, that it accepts a response like application/json
.
The name of the method itself, translated, is something like: "Want JSON?".
Already the method ajax
is intended to verify that the request is a Xml Http Request, that is, if it was done through Ajax.
Note that, an ajax request, can be returned HTML, XML, JSON, among other things.
In the specific case of those who use Angularjs on the front end, I would strongly recommend using wantJson()
, because angular always sends this header accept
on each request.
ajax
allows anothercontent-type
than JSON?– Jefferson Quesado
@Jeffersonquesado is exactly the answer I want to be given. A lot of people who use Laravel think they’re the same.
– Wallace Maxters
@Jeffersonquesado ajax uses any type passed in accepts, ie can work with text, xml, json and "binaries"
– Guilherme Nascimento