Sometimes we need to find out the request type in the Laravel application. Like sometimes you may check the post request type or patch request type or maybe the Ajax request type. But you do not know how to check the request type in Laravel.
In this tutorial, I will show you how to check request is Ajax or not in Laravel, and also I will show you how to check the request type in Laravel. You already know that there are multiple request types.
Let's see the below example code of how to check ajax request in laravel 10:
<?php
namespace App\Http\Controllers\Admin;
use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\CreateCategoryRequest;
use App\Http\Requests\UpdateCategoryRequest;
class CategoryController extends Controller
{
/**
* Summary of index
* @param Category $category
* @param Request $request
* @return mixed
*/
public function index(Category $category, Request $request)
{
if ($request->ajax()) {
//request is ajax request
}
return view('admin.category.index');
}
}
Now see the below example code of how to check post request type in laravel:
<?php
namespace App\Http\Controllers\Admin;
use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\CreateCategoryRequest;
use App\Http\Requests\UpdateCategoryRequest;
class CategoryController extends Controller
{
/**
* Summary of index
* @param Category $category
* @param Request $request
* @return mixed
*/
public function index(Category $category, Request $request)
{
if ($request->method() === 'POST') {
//request is POST request
}
return view('admin.category.index');
}
}
Now see the below example code of how to check get request type in laravel:
<?php
namespace App\Http\Controllers\Admin;
use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\CreateCategoryRequest;
use App\Http\Requests\UpdateCategoryRequest;
class CategoryController extends Controller
{
/**
* Summary of index
* @param Category $category
* @param Request $request
* @return mixed
*/
public function index(Category $category, Request $request)
{
if ($request->method() === 'GET') {
//request is GET request
}
return view('admin.category.index');
}
}
Conclusion
Now we know how to check ajax request in laravel 10. Hope after completing this how to check request is ajax or not in laravel tutorial, you can able to check request type in laravel 10.