skip to Main Content

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'
   ]);
}

2

Answers


  1. 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'
       ]);
    }
    
    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search