Hello, developers, In this article, we'll see how to get a request header in laravel 10. Here, we'll see the header value in laravel 10. In this tutorial, we'll create an endpoint to retrieve all headers or specific ones effortlessly.
Here, we'll use the header() request method and get the header request value.
Laravel 10 Get Request Header
Define a route in your routes/web.php
file or routes/api.php
file, depending on whether you are working with a web or API route.
use App\Http\Controllers\UserController;
Route::get('/get-request-headers', [UserController::class, 'getRequestHeaders']);
Now, we'll create a controller using the following command.
php artisan make:controller UserController
Next, open the controller and implement the method to retrieve request headers:
app/Http/Controller/UserController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function getRequestHeaders(Request $request)
{
$headers = $request->header(); /* Getting All Headers from request */
$header = $request->header('Accept'); /* Getting Singe Header value from request */
return response()->json($headers);
}
}
Now, run the laravel 10 application using the following command.
php artisan serve
If you want to retrieve a specific header, you can use the header
method on the request:
public function getRequestHeaders(Request $request)
{
// Retrieve a specific header
$contentType = $request->header('Content-Type');
return response()->json(['Content-Type' => $contentType]);
}
To handle cases where a header may not exist, you can use the has
method:
public function getRequestHeaders(Request $request)
{
// Check if a header exists
if ($request->headers->has('Authorization')) {
$authorizationHeader = $request->header('Authorization');
return response()->json(['Authorization' => $authorizationHeader]);
} else {
return response()->json(['message' => 'Authorization header not present'], 400);
}
}
You might also like:
- Read Also: Laravel 10 REST API CRUD Operation
- Read Also: How to Get Last 15 Records in Laravel 10
- Read Also: How to Create AJAX Pagination in Laravel 10
- Read Also: How to Create Bar Chart in Laravel 10 using Apexcharts