DEV Community

Morcos Gad
Morcos Gad

Posted on

Laravel Request wantsJson() - isJson()

Today I want to share this information with you, in the hope that it will help you in your future projects.

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
use Illuminate\Http\Request;

If you want to check if response needs to be JSON
If you want to check if request is of JSON type

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index(Request $request)
    {
        dd($request->wantsJson()); // output:- false
    }
}
Enter fullscreen mode Exit fullscreen mode

Not all AJAX requests expect a JSON response, so utilizing request()->ajax() is useful where you want to determine if the request was an XmlHttpRequest or not, but the response doesn't care about JSON or not.

Not all requests that contain JSON expect a JSON response. so if you don't care about whether or not the response wants JSON back, but want to determine if JSON was sent in the request, then isJson() is useful for you.

Not all requests that want JSON responses are AJAX driven, so wantsJson is useful in the case where you want to return JSON data, but you don't care how the request came to your server.

I hope you enjoyed the code.

Top comments (0)