Laravel Guzzle Middleware for requests headers

Viewed 44

I have a controller that sends http requests to external urls via Guzzle. And there are many such controllers, how to make a middleware that will add a certain header to each request, instead of adding method 123 to the zoo in each controller

My Controller:

class PostController extends Controller {
public function getLastRecord() {
    $lastRec = Post::latest('created_at')->first();

    $body = collect([$lastRec])->map(function($record) {
        return [
            'id' => $record->post_id,
            'rec_name' => $record->post_name,
            'user' => $record->user_id,
        ];
    })->toArray();

    $response = Http::withToken('1Asaciry$rsW$')->post('http://post.com', $body);       

    return $response;
}

}

And I don't want to use withToken, I just want to use ::post, but in each request, the "Authorization" header will be added: "1as City$rsW$".

1 Answers

You can create a custom class or helper function or controller method to handle this and encapsulate what you need in all guzzle requests

function myHttp()
{
return Http::withToken('1Asaciry$rsW$') ;
}

Then chain to it rest of request

$response= myHttp()->post()
Related