44

I noticed that Laravel has a neat method Request::wantsJson - I assume when I make the request I can pass information to request a JSON response, but how do I do this, and what criteria does Laravel use to detect whether a request asks for JSON ?

Martyn
  • 6,031
  • 12
  • 55
  • 121

1 Answers1

75

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"})
Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
  • 3
    Usually you want to use [$request->expectsJson()](https://laravel.com/api/6.x/Illuminate/Http/Concerns/InteractsWithContentTypes.html#method_expectsJson) instead. This is will also check if you have received an AJAX request. – igaster Jan 14 '20 at 12:14
  • 1
    Dart/Flutter: `var headers = Map(); headers.putIfAbsent(HttpHeaders.acceptHeader, () => 'application/json');` – user3563059 Jan 30 '20 at 01:31
  • 1
    can you put an example with `Request::create()` in laravel ? – Tharaka Dilshan Dec 21 '20 at 02:54