Laravel 10 - How to retrieve Header Information
Laravel 10 - How to retrieve Header Information
In this tutorial, we will discuss how to retrieve header information in Laravel 10, which is useful for managing API requests, authentication, and custom headers.
If you're a video person, feel free to skip the post and check out the video instead!
Step # 1 : Create fresh Laravel project or use existing project.
Two commands to create fresh laravel project
Global Command : laravel new header
Or use
Non Global Command : composer create-project laravel/laravel --prefer-dist header
Step # 2 : Access the project.
Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
Git Bash : cd c:xampp/htdocs/header
Next, install the required dependencies and run the Laravel Vite development server for front-end assets:
Command : npm install && npm run dev
In a new terminal window or tab (while keeping the Vite server running), navigate to the same project directory to execute further Laravel commands.
Step # 3 : Create a route.
Import HeaderController class
use App\Http\Controllers\HeaderController;
create route.
Route::get('/', [HeaderController::class, 'index']);
Step # 5 : Create a controller.
Command : php artisan make:controller HeaderController
Update the HeaderController with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HeaderController extends Controller
{
public function index(Request $request)
{
$header = $request->header();
dd($header);
}
}
Step # 6 : It's time to test.
Start the Laravel development server.
Command : php artisan serve.
Access below URL
127.0.0.1:8000
If you want to get a specific value. Update the index method like below
public function index(Request $request)
{
$userAgent = $request->header('user-agent');
dd($userAgent);
}
Or you can use Apache request headers. Update the index method like below
public function index(Request $request)
{
$headerInfo = apache_request_headers();
dd($headerInfo);
}
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments