How to check request is Ajax or not in Laravel?

Today now in this post i will show you How to check request is Ajax or not in Laravel? Sometimes, we may need to check the request is ajax or not in any version laravel 5, laravel 6, laravel 7 and laravel 8. If we are want to call same method but if the request is ajax then we need to perform different, then we can do this by using $request object.

In Laravel $request object is provide that method to check the request is ajax or not. Now in the following example we can see how it’s works.

We can check this directly from the Request facade and also from the request object, both are same, so let’s see here in the bellow example.

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

Read Also: How to show Line Chart by using Google Charts API in Laravel

Thanks for read. I hope it help you. For more you can follow us on facebook

close

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →