In this article we will learn to get headers data from request in laravel. Http Request headers are used to send the information to server like what type of content clients accept, Content type or authorizations technique used to validate the request.To retrieve the headers data in laravel we need to call header method of request class.
Sometimes we send some hidden information like token or cookies in the headers which we want to access at server side so to access that in laravel we use header
method of request as follow
$request->header(); // get all headers
or
$data = request()->header('header_name'); // array list of headers
$data['field_name'];
Let’s understand it with example step by step
Step 1: Create a fresh laravel project
Open a terminal window and type below command to create a new project
composer create-project --prefer-dist laravel/laravel blog
You can also read this to start with new project
Step 2: Create Route
Next, create a route a and define a inline function in the routes as follow
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
Route::post("/send-header-request",function(Request $request ){
$data = $request ->header();
dump($request->header('Accept'));
dd($data);
});
Step 3 : Create Javascript Fetch API Call
To test and send a request in json post format we need to call it from either from client side or server side so we are using here JavaScript fetch
method
<script>
fetch('http://localhost:8000/send-json-request', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({test: 1, b: 'Textual content'})
}).then(data=>{
});
</script>
ScreenShot: