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

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Hello Dev’s, Today in this article, we will know about how to check request is ajax or not in controller method in laravel application. Now I will teach you know how to determine a request is ajax or not in Laravel application. Here i will show you How to check request is ajax or not in Laravel 8.

Sometime we need to check a request is ajax or not in our laravel application. If it is a ajax request then we need response data only and if request is not ajax then we need to response complete view in our application.

So by using ajax() method in Laravel application, We can check a request is ajax or not in controller.

In Laravel Request class has many methods to read as HTTP request for the current request. So we can also check if request is over https or request has json content type.

So we can use directly Request facade that grant we can access to the current request or we can use instance of Request Class.

Example 1:

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

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

Example 2 :

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

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

Example 3 :

if (Request::secure())
{
    //
}

Read Also : How to get last executed mysql query in laravel?

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

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 →