Whether it is a good practice or not depends on the case.
In my case it is necessary that all requests made to the service have a request id. If the id does not exist then I have to create a new one. All this is to follow the requests through the logs (of various micro-services) when an exception is thrown.
This is the way I updated the Headers (in Lumen, but i think es the same for laravel):
use Closure;
use Illuminate\Http\Request;
use Webpatser\Uuid\Uuid;
class CreateRequestIdMiddleware
{
public const HEADER_NAME = 'request-id';
public function handle(Request $request, Closure $next)
{
$requestId = $request->header(self::HEADER_NAME);
if ($requestId === null) {
$uuid = Uuid::generate(4)->string;
$request->headers->set(self::HEADER_NAME, $uuid);
}
return $next($request);
}
}
So i can access it i my controller
namespace App\Http\Controllers;
use App\Offer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
class OfferController extends Controller
{
public function all(Request $request): JsonResponse
{
dd($request->header('request-id'));
/* some code */
}
}
The class Illuminate\Http\Request extends from Symfony\Component\HttpFoundation\Request that has the public attribute $headersof type Symfony\Component\HttpFoundation\HeaderBag.
HeaderBag have the method set defined as
public function set($key, $values, $replace = true) { /* ... */ }