The wantsJson() method checks the Accept HTML header for the string application/json and returns true if it is set. The isJson() method checks that the HTML header CONTENT_TYPE contains the string /json and returns true if it is found. Both methods are found in vendor/laravel/framework/src/Illuminate/Http/Request.php.
Once the application has been bootstrapped and all service providers have been registered, the Request will be handed off to the router for dispatching. The router will dispatch the request to a route or controller, as well as run any route specific middleware.
Laravel Request: expectsJson() This function determines if current request expects a json response.
It uses the Accept
header sent by the client to determine if it wants a JSON response.
Let's look at the code :
public function wantsJson() {
$acceptable = $this->getAcceptableContentTypes();
return isset($acceptable[0]) && $acceptable[0] == 'application/json';
}
So if the client sends a request with the first acceptable content type to application/json
then the method will return true.
As for how to request JSON, you should set the Accept
header accordingly, it depends on what library you use to query your route, here are some examples with libraries I know :
Guzzle (PHP):
GuzzleHttp\get("http://laravel/route", ["headers" => ["Accept" => "application/json"]]);
cURL (PHP) :
$curl = curl_init();
curl_setopt_array($curl, [CURLOPT_URL => "http://laravel/route", CURLOPT_HTTPHEADER => ["Accept" => "application/json"], CURLOPT_RETURNTRANSFER => true]);
curl_exec($curl);
Requests (Python) :
requests.get("http://laravel/route", headers={"Accept":"application/json"})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With