How to check request is Ajax or not in Laravel 5

Sometimes, we need to check request is ajax or not in Laravel 5. If you want to call the same method but if the request is ajax then you perform differently, then you can do by using $request object.

In Laravel 5 $request object provides a method to check request is ajax or not, In the following example you can see how it works.
You can check directly from Request facade and also from the request object, both are same, so let's see below example.

Example 1:

public function index(Request $request)
{
    if($request->ajax()){
        return response()->json(['ajax']);
    }
    return response()->json(['http']);
}

Example 2:

public function index()
{
    if(Request::ajax()){
        return response()->json(['ajax']);
    }
    return response()->json(['http']);

}

Comments

Popular posts from this blog

Laravel 5 Chart example using Charts Package

Laravel Stats Tracker

PHPMyBackup - A PHP MySQL differential backup script