How to get Headers from Request in Laravel

1528
api headers

While building an API, we may encounter a situation to pass information in the header and access them through request. Well, this process is straightforward. In this short article, we will see how we can access the header information in Laravel.

We can access the header information using the Request class object. First of all we need to instantiate the object, then by giving header name, we can retrieve the information associated with it. Let’s check the following example:

First, we will pass values attached with keys sample-token and another-test in Postman as in the image below.

Then, we can access these two custom headers information as below:

/**
 * Store the information.
 *
 * @return void
 */
public function store(Request $request)
{
    //prints out all header information
    $headers = $request->header();    

    //get sample-token value
    $sample_token = $request->header('sample-token');

    //get another-test value
    $another_test = $request->header('another-test');
    .........
}

Also, if we want to get the bearer authorization token, we can do using bearerToken() method. It will take token without bearer word. However, if you want to get with Bearer word, we can do so using Authorization keyword.

public function store(Request $request)
{
    //get bearer authorization token without Bearer word
    // e.g. 9rJp2TWvTTpWy535S1Rq2DF0AEmYbEotwydkYCZ3
    $token = $request->bearerToken();    

    //get bearer authorization token with Bearer word
    //e.g. Bearer 9rJp2TWvTTpWy535S1Rq2DF0AEmYbEotwydkYCZ3
    $token = $request->header('Authorization');

    .........
}
Read More Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.