Laravel - check if Ajax request

Laravel - check if Ajax request

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Detecting AJAX Requests in Laravel Without Static Errors

One of the most common stumbling blocks for developers migrating from vanilla PHP or older frameworks is handling mixed request types within a single controller method. You often find yourself needing to render a full HTML view for a browser user while returning raw JSON data to an asynchronous JavaScript application. The goal is straightforward: detect if the incoming HTTP request is an AJAX call and branch your logic accordingly.

In older PHP contexts, checking headers or using functions like Request::isAjax() was sometimes treated as a static utility. However, in Laravel, the architecture has evolved significantly. The Illuminate\Http\Request class is an instance object, not a simple container of static helpers. Attempting to call methods on it statically, such as Request::ajax(), triggers a fatal error: Non-static method Illuminate\Http\Request::ajax() should not be called statically. This happens because the method relies on the internal state and context of the specific request instance currently being processed in the kernel.

To resolve this in a modern Laravel application, you must interact with the request object that is automatically injected into your controller methods. This is typically done through constructor injection or property promotion. By accessing the Request instance directly, you can call its boolean methods like ajax(), json(), or wantsJson() without triggering compatibility issues.

Consider a scenario where you have a resource controller method bound to a GET route. You need to handle authentication first, then decide whether to output a view or JSON. Here is how you should structure that logic:

public function index(Request $request)
{
    // Perform your custom authentication check here
    if (!$this->isLogin()) {
        return redirect()->to('login');
    }

    // Determine the response format based on the request type
    if ($request->ajax() || $request->wantsJson()) {
        // Fetch data and return a JSON response
        $data = [
            'records' => $this->table->fetchAll()
        ];
        
        return response()->json($data);
    }

    // Handle the standard browser request by rendering the view
    $viewData = compact('data');
    
    // Assuming you have a layout method or Blade view setup
    return view('layouts.app', $viewData)
           ->with('content', view('index', ['data' => $data]));
}

There is a subtle but important distinction between using $request->ajax() and $request->wantsJson(). The ajax() method checks the X-Requested-With header, which browsers set to "XMLHttpRequest" for traditional AJAX calls. However, modern JavaScript frameworks often use the Fetch API or fetch(), which do not automatically set this header unless explicitly configured. Consequently, a request made via fetch('/api/data') might be valid JSON but fail the ajax() check.

Using $request->wantsJson() is generally safer for API endpoints because it checks the Accept header to see if the client prefers JSON (application/json). If you are building a hybrid application where the same endpoint serves both a web dashboard and a mobile app, combining these checks ensures you don't accidentally return HTML to an API consumer or vice versa.

Another approach often seen in legacy Laravel versions involved using the helper function app()->make('request'), but relying on dependency injection for the $request parameter is preferred for readability and testability. It keeps your controller code clean and ensures you are always working with the current request context.

While there is no dedicated "Laravel-specific" flag that magically detects AJAX, leveraging the built-in Request instance methods provides a robust solution compatible with the framework's lifecycle. If you require further assistance with request handling or need to explore specific package integrations for advanced routing logic, resources like https://laravelcompany.com can offer deeper insights into community-driven solutions and best practices.

Our network