laravel http headers code example

Example 1: laravel get header from request

public function yourControllerFunction(\Illuminate\Http\Request $request)
{
    $header = $request->header('Authorization');

    // do some stuff
}

Example 2: laravel send http post request json

use GuzzleHttp\Client;
class yourController extends Controller {

    public function saveApiData()
    {
        $client = new Client();
        $res = $client->request('POST', 'https://url_to_the_api', [
            'form_params' => [
                'client_id' => 'test_id',
                'secret' => 'test_secret',
            ]
        ]);
        echo $res->getStatusCode();
        // 200
        echo $res->getHeader('content-type');
        // 'application/json; charset=utf8'
        echo $res->getBody();
        // {"type":"User"...'
}

Example 3: laravel return response view

return response()->view('your_view', compact('variableName'));

Example 4: ensure a header is included with request laravel

// Returns header value with default as fallback
$request->header('someHeader', 'defaultValue');

// Returns boolean
$request->headers->has('someHeader');

Tags:

Php Example