How to get request headers in 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.

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment