How to check request is ajax or not in Laravel 8

  699 views   1 year ago Laravel

Sometime in your Laravel application, you might need to check if request is ajax then response json data else return view in response. This helps to manage Ajax request in same route when you want to load view first and then then send ajax request to view data.

In this article, we will learn how you can check request is ajax or not in controller method. In Laravel, ajax() method checks if request is from ajax or not and return true or false.

You can use Request facade that checks current request or you can use Request instance.

Request facade example:

/**
 * Load resource data.
 *
 * @return void
 */
public function index(Request $request)
{
    if($request->ajax()) {
        // ajax request
        return response()->json(['status' => 'success']);
    }

    return response()->json(['status' => 'fail']);
}

Request instance example.

/**
 * Load resource data.
 *
 * @return void
 */
public function index()
{
    if(Request::ajax()) {
        // ajax request
        return response()->json(['status' => 'success']);
    }

    return response()->json(['status' => 'fail']);
}

I hope it will help you. Thanks for giving time in reading the article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]