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.
/**
* 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']);
}
/**
* 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.
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]
Get Current time and date in React
In this tutorial, we will discuss how to...Laravel 5.5 - Delete Confirm Bootstrap jQuery Model
Hello, everyone in this article we are s...How to Check for a Hash (#) in a URL using JavaScript
Use the Window.location Property You...How to Remove index.php from URL in Laravel
In this article, i will share with you h...How to upload files in ReactJs with Example
File uploading in React.js For an...