Laravel - check if Ajax request

Maybe this helps. You have to refer the @param

         /**       
         * Display a listing of the resource.
         *
         * @param  Illuminate\Http\Request $request
         * @return Response
         */
        public function index(Request $request)
        {
            if($request->ajax()){
                return "AJAX";
            }
            return "HTTP";
        }

$request->wantsJson()

You can try $request->wantsJson() if $request->ajax() does not work

$request->ajax() works if your JavaScript library sets an X-Requested-With HTTP header.

By default Laravel set this header in js/bootstrap.js

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

In my case, I used a different frontend code and I had to put this header manually for $request->ajax() to work.

But $request->wantsJson() will check the axios query without the need for a header X-Requested-With:

// Determine if the current request is asking for JSON. This checks Content-Type equals application/json.
$request->wantsJson()
// or 
\Request::wantsJson() // not \Illuminate\Http\Request

You are using the wrong Request class. If you want to use the Facade like: Request::ajax() you have to import this class:

use Illuminate\Support\Facades\Request;

And not Illumiante\Http\Request


Another solution would be injecting an instance of the real request class:

public function index(Request $request){
    if($request->ajax()){
        return "AJAX";
    }

(Now here you have to import Illuminate\Http\Request)


To check an ajax request you can use if (Request::ajax())

Note: If you are using laravel 5, then in the controller replace

use Illuminate\Http\Request;

with

use Request; 

I hope it'll work.

Tags:

Php

Laravel