Laravel Request: wantsJson()

Asked: 20 days ago


This function finds if the request is asking for JSON in return.


public function wantsJson():bool


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

Example-1: Use of wantsJson function in Laravel Controller


namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
    public function index(Request $request)
        dd($request->wantsJson()); // output:- false

Example-2: Use of wantsJson function using request()

Following example can be used anywhere in Laravel app:

namespace App\Helpers;

use Illuminate\Http\Request;

class Test 
    public function __construct() 
        dd(request()->wantsJson()); // output:- false
Viewed: 44 times
Liked: 1 times