As a beginner, we don’t know to check if the request is Ajax or not in Laravel application but using this Laravel check if request is Ajax example, will definitely clear your doubt. We have added an easy syntax and full example to learn How to check request is Ajax or not in Laravel.
So, go through the below example to check the request type Ajax or HTTP which is coming from frontend in our Laravel controller.
#Syntax:
For checking if the request is Ajax in Laravel we just need to check $request->ajax() with the if condition.
public function index(Request $request)
{
if ($request->ajax()) {
return response()->json([ 'message' => 'Return Ajax request' ]);
}
return view('your_view_mame');
}
#Example
Here is how can you use both Ajax and HTTP request code to check if request is ajax or not in laravel.
See Also: Laravel Ajax CRUD Example from Scratch
Support you are showing the list with HTTP request and when the ajax request appears you also need to show the list page. So you can use the below code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
class ProductController extends Controller
{
public function index(Request $request)
{
$products = Product::orderBy('id','desc')->paginate(10);
if ($request->ajax()) {
return response()->json([
'html' => view('product-list', compact('products'))->render()
]);
}
return view('products', compact('products'));
}
}
I think your concern laravel check if request is ajax or not is cleared now. If you have any question let us know in the comment section.