[10.x] Add global middleware to Http client
#47525
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
💡 Updated!
This PR allows an application to add Guzzle middleware that is applied to every request made via the
Httpclient. It also introduces some nicer named methods to add request / response only middleware.Read more about Guzzle middleware in their docs.
As an example, an application may globally set a
User-Agentheader, to be a good citizen of the Internet. To do this, you may add a global "request" middleware:This will mean that every outgoing request will now have the
User-Agent: Laravel Framework/1.0header.Here is another example, showing the addition of a global "response" middleware.
It is also possible, of course, to add a complete middleware that wraps both the request and response cycle. As an example, the following middleware will add a response header including the duration of the request in milliseconds. The value may also be logged or recorded elsewhere.
Something like the above would also be possible via the
on_statsGuzzle option.The global middleware is also useful for logging and inspection of outgoing requests or incoming responses, although this is also possible by listening to events, but now we have a unified way of doing this.
I've also introduced named middleware methods for the request / response middleware to the
PendingRequestclass. These make adding middleware feel more at home in Laravel, IMO, when compared to having to reference theGuzzleHttp\Middlewareclass directly.Here is a before and after of using the new named methods for a "request" middleware:
You can see the currently documented way in the screenshot below. I feel these named methods greatly streamline the user-facing API.
Here is the full API for adding middleware to Http requests after this PR:
Similar PRs:
Http::configure()method #40332