l2t

Laravel Request: expectsJson()

Asked: 23 days ago

Defination

This function determines if current request expects a json response.

Syntax

public function expectsJson():bool

Usecases

  • If you want to check that request has a header called "Accept" and value is "application/json"
  • This is useful if you are building REST API app where you want to check whether request type is json

Example-1: Use of expectsJson function in Laravel Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

Example-2: Use of expectsJson 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()->expectsJson()); // output:- false
    }
}
Viewed: 61 times
Liked: 2 times