Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Laravel know Request::wantsJson is a request for JSON?

People also ask

What is wantsJson laravel?

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.

How does request work in laravel?

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.

What is request expectsJson () in laravel?

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"})