Get request header in Laravel 9

0
3045
Get request header in Laravel 9
Get request header in Laravel 9

In this post, I will show you how to get request header in Laravel 9.

There are several ways to get headers in Laravel 9, you can make use from any of these.

1. Inject an instance of Illuminate\Http\Request class:

namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Illuminate\Http\Response;
 
class SampleController extends Controller
{
    public function index(Request $request): Response
    {
        $userAgent = $request->header('User-Agent');
        $ip = $request->header('X-Forwarded-For');
 
        return response()->json(['userAgent' => $userAgent, 'ip' => $ip);
    }
}

2. Use Illuminate\Support\Facades\Request

namespace App\Http\Controllers;
 
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Request;
 
class SampleController extends Controller
{
    public function index(): Response
    {
        $userAgent = Request::header('User-Agent');
        $ip = Request::header('X-Forwarded-For');
 
        return response()->json(['userAgent' => $userAgent, 'ip' => $ip);
    }
}

3. Access headers from the global environment variable $_SERVER

namespace App\Http\Controllers;
 
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Request;
 
class SampleController extends Controller
{
    public function index(): Response
    {
        $userAgent = $_SERVER['HTTP_USER_AGENT'];
        $ip = $_SERVER['REMOTE_ADDR'];
 
        return response()->json(['userAgent' => $userAgent, 'ip' => $ip);
    }
}

4. Use getallheaders() or apache_request_headers()

namespace App\Http\Controllers;

class SampleController extends Controller
{
    public function getHeaders()
    {
        $headers = getallheaders();

        $userAgent = $headers['User-Agent'];
        $lang = $headers['Accept-Language'];

        return response()->json([
            'User-Agent' => $userAgent,
            'Accept-Language' => $lang,
        ]);
    }
}

It is recommended to use the 1st method to get request header in Laravel 9; however, you can use any of them.

Have fun!