Laravel Get Headers From Request Example

  933 views   6 months ago Laravel

In Laravel application, there are many ways you can get request headers. We will discuss about few ways from them.

1. Illuminate\Http\Request object

Laravel provides many details in Illuminate\Http\Request class object. You can simply get headers details using headers() method. This will return all headers in array.

use Illuminate\Http\Request;

/** 
 * Show the resource list 
 * 
 * @return void
 */ 
public function index(Request $request)
{
    $headers = $request->header();

    // or pass parameter to get specific header
    $user_agent = $request->header('user-agent');
}

2. \Request class header() function

You can use static header() method from the \Request class as below.

/** 
 * Show the resource list 
 * 
 * @return void
 */ 
public function index(Request $request)
{
    $headers = \Request::header();

    // or pass parameter to get specific header
    $user_agent = \Request::header('user-agent');
}

3. apache_request_headers() method

apache_request_headers() is PHP method that returns the header data. You can use this method to get headers.

/** 
 * Show the resource list 
 * 
 * @return void
 */ 
public function index(Request $request)
{
    $headers = apache_request_headers();

    dd($headers);
}

4. Global getallheaders() method

The getallheaders() method is alias for apache_request_headers() and returns the same data as above. This will return array of headers.

/** 
 * Show the resource list 
 * 
 * @return void
 */ 
public function index(Request $request)
{
    $headers = getallheaders();

    dd($headers);
}

So, this is most common ways to get headers in Laravel. I hope you liked this small article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]