How to check if request is ajax or not in Laravel 8

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. 

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment