How to Get Request Header in Laravel?
Hello Friends,
This tutorial shows you how to get request header value in laravel. Here you will learn how to get request header in laravel. Iām going to show you about laravel get all headers from request. you'll learn laravel get header from request.
You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.
Sometimes, we need to get headers value from request in the laravel application. in this example, i will give you very simple example of getting request header using header() method of request.
So, let's see the below example:
Step 1: Create Route
In this step, we will add one api/posts route to return all headers from request in laravel. So, let's add a new route to that file.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('api/posts', [PostController::class, 'index']);
Step 2: Create Controller
in the next step, now we have created a new controller as PostController and write index method on it like as below, So let's create a controller:
app/Http/Controllers/PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$headers = $request->header(); /* Getting All Headers from request */
$header = $request->header('Accept'); /* Getting Singe Header value from request */
return response()->json($headers);
}
}
Run Laravel App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web postman, type the given URL and view the app output:
http://localhost:8000/api/posts
Postman Output:
I hope it can help you...