How to Check Request is Ajax or Not in Laravel?

By Hardik Savani April 16, 2024 Category : Laravel Ajax

Hi Folks,

Now, let's see post of laravel check ajax request. In this article, we will implement a laravel check if request is ajax. you can understand a concept of check if request is ajax laravel. you will learn laravel ajax request check.

Sometimes, we need to check request is ajax or not in laravel 5, laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11. If you want to call same method but if request is ajax then you perform different, then you can do by using $request object.

In Laravel $request object provide method to check request is ajax or not, In following example you can see how it's works.

You can check directly from Request facade and also from request object, both are same, so let's see bellow example.

Example 1:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ItemController extends Controller

{

/**

* Display a listing of the resource.

*/

public function index(Request $request)

{

if($request->ajax()){

return response()->json(['request' => 'ajax']);

}

return response()->json(['request' => 'http']);

}

}

Example 2:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ItemController extends Controller

{

/**

* Display a listing of the resource.

*/

public function index(Request $request)

{

if(Request::ajax()){

return response()->json(['request' => 'ajax']);

}

return response()->json(['request' => 'http']);

}

}

I hope it can help you...

Tags :
Shares