Home > Back-end >  how do I set headers programmatically on Laravel Http Client?
how do I set headers programmatically on Laravel Http Client?

Time:10-20

I want to add some headers but can't find it on the docs

$httpRequest = Http::baseUrl(config('api_base_url'))
            ->withHeaders([
                'Authorization' => 'Bearer ' . $accessToken,
            ]);

// can i do something like this?
if ($var === 'me') {
   $httpRequest->pushToExistingHeaders([
       "Content-Type" => 'multipart/form-data'
   ]);
}

CodePudding user response:

You can use withHeaders again to merge your headers conditionally with the previous headers as shown in the Laravel code. This is because it adds to the previous headers and doesn't replace them.

This is how other methods like accept, content-type are accomplishing this.

<?php

$httpRequest = Http::baseUrl(config('api_base_url'))
               ->withHeaders([
                'Authorization' => 'Bearer ' . $accessToken,
               ]);


if ($var === 'me') {
   $httpRequest->withHeaders([
       "Content-Type" => 'multipart/form-data'
   ]);
}

CodePudding user response:

Make header content as array variable. For example

if($var === "me") {
     $headers = [
        'Authorization' => 'Bearer ' . $accessToken,
        "Content-Type" => 'multipart/form-data'
     ];
} else {
     $headers = [
        'Authorization' => 'Bearer ' . $accessToken
     ];
}


$httpRequest = Http::baseUrl(config('api_base_url'))
->withHeaders($headers);
  • Related