whonoes
whonoes

Reputation: 503

Adding headers to internal requests in Laravel 4

I have an API centric setup built with Laravel 4, consisting of a REST API, frontend and adminpanel. Both frontend and adminpanel are consuming the API using internal requests.

I make internal requests like this:

$request = Request::create($endpoint, $method, $parameters, $cookies, $files, $server, $content);
$this->response = Route::dispatch($request);

And everything works fine.

Now I want to secure the API using an approach similar to AWS's and when I create the request above I want to also set some custom headers (api key, signature, timestamp).

I have not found a way to add headers to a custom request. Is this possible when using internal requests?

Upvotes: 3

Views: 6063

Answers (2)

whonoes
whonoes

Reputation: 503

Turns out setting headers is as simple as doing

$request->headers->set('MyHeaderName', 'header value');

before dispatching the request.

The catch (and the reason this did not work when I tried) is that in the API I have to use Route::getCurrentRequest() to get my custom request (as opposed to just asking the Request facade):

$request = Route::getCurrentRequest();
$all_headers = $request->header();
$specific_header = $request->header("SomeHeaderName");

Upvotes: 6

Jeemusu
Jeemusu

Reputation: 10533

You could set the headers using a application event in your filters.php

App::after(function($request, $response)
{
   $response->headers->set('key','value');
});

If you find your using a lot of them, moving them into their own service provider may provide for a better structure.

Upvotes: 1

Related Questions