跳到內容

HTTP 用戶端

簡介

Laravel 提供了一個圍繞 Guzzle HTTP 用戶端 的富有表現力且極簡的 API,讓您可以快速發出外送 HTTP 請求,以便與其他 Web 應用程式進行通訊。Laravel 對 Guzzle 的封裝專注於其最常見的使用案例和絕佳的開發人員體驗。

發出請求

要發出請求,您可以使用 Http facade 提供的 headgetpostputpatchdelete 方法。首先,讓我們檢視如何向另一個 URL 發出基本的 GET 請求

1use Illuminate\Support\Facades\Http;
2 
3$response = Http::get('http://example.com');

get 方法會傳回 Illuminate\Http\Client\Response 的實例,其中提供各種可用於檢查回應的方法

1$response->body() : string;
2$response->json($key = null, $default = null) : mixed;
3$response->object() : object;
4$response->collect($key = null) : Illuminate\Support\Collection;
5$response->resource() : resource;
6$response->status() : int;
7$response->successful() : bool;
8$response->redirect(): bool;
9$response->failed() : bool;
10$response->clientError() : bool;
11$response->header($header) : string;
12$response->headers() : array;

Illuminate\Http\Client\Response 物件也實作了 PHP ArrayAccess 介面,讓您可以直接在回應中存取 JSON 回應資料

1return Http::get('http://example.com/users/1')['name'];

除了上面列出的回應方法外,以下方法可用於判斷回應是否具有給定的狀態碼

1$response->ok() : bool; // 200 OK
2$response->created() : bool; // 201 Created
3$response->accepted() : bool; // 202 Accepted
4$response->noContent() : bool; // 204 No Content
5$response->movedPermanently() : bool; // 301 Moved Permanently
6$response->found() : bool; // 302 Found
7$response->badRequest() : bool; // 400 Bad Request
8$response->unauthorized() : bool; // 401 Unauthorized
9$response->paymentRequired() : bool; // 402 Payment Required
10$response->forbidden() : bool; // 403 Forbidden
11$response->notFound() : bool; // 404 Not Found
12$response->requestTimeout() : bool; // 408 Request Timeout
13$response->conflict() : bool; // 409 Conflict
14$response->unprocessableEntity() : bool; // 422 Unprocessable Entity
15$response->tooManyRequests() : bool; // 429 Too Many Requests
16$response->serverError() : bool; // 500 Internal Server Error

URI 模板

HTTP 用戶端也允許您使用 URI 模板規範 建構請求 URL。若要定義可由您的 URI 模板擴充的 URL 參數,您可以使用 withUrlParameters 方法

1Http::withUrlParameters([
2 'endpoint' => 'https://laravel.dev.org.tw',
3 'page' => 'docs',
4 'version' => '11.x',
5 'topic' => 'validation',
6])->get('{+endpoint}/{page}/{version}/{topic}');

傾印請求

如果您想要在傳送外送請求實例之前傾印它並終止指令碼的執行,您可以將 dd 方法新增至請求定義的開頭

1return Http::dd()->get('http://example.com');

請求資料

當然,在發出 POSTPUTPATCH 請求時,通常會連同請求一起傳送額外資料,因此這些方法會接受資料陣列作為其第二個引數。依預設,資料將使用 application/json 內容類型傳送

1use Illuminate\Support\Facades\Http;
2 
3$response = Http::post('http://example.com/users', [
4 'name' => 'Steve',
5 'role' => 'Network Administrator',
6]);

GET 請求查詢參數

發出 GET 請求時,您可以將查詢字串直接附加到 URL,或將索引鍵/值組的陣列作為第二個引數傳遞給 get 方法

1$response = Http::get('http://example.com/users', [
2 'name' => 'Taylor',
3 'page' => 1,
4]);

或者,可以使用 withQueryParameters 方法

1Http::retry(3, 100)->withQueryParameters([
2 'name' => 'Taylor',
3 'page' => 1,
4])->get('http://example.com/users')

傳送表單 URL 編碼請求

如果您想要使用 application/x-www-form-urlencoded 內容類型傳送資料,您應該在發出請求之前呼叫 asForm 方法

1$response = Http::asForm()->post('http://example.com/users', [
2 'name' => 'Sara',
3 'role' => 'Privacy Consultant',
4]);

傳送原始請求本文

如果您想要在發出請求時提供原始請求本文,您可以使用 withBody 方法。內容類型可以透過方法的第二個引數提供

1$response = Http::withBody(
2 base64_encode($photo), 'image/jpeg'
3)->post('http://example.com/photo');

多部分請求

如果您想要以多部分請求傳送檔案,您應該在發出請求之前呼叫 attach 方法。此方法接受檔案的名稱及其內容。如果需要,您可以提供第三個引數,該引數將被視為檔案的檔案名稱,而第四個引數可用於提供與檔案關聯的標頭

1$response = Http::attach(
2 'attachment', file_get_contents('photo.jpg'), 'photo.jpg', ['Content-Type' => 'image/jpeg']
3)->post('http://example.com/attachments');

您可以傳遞串流資源,而不是傳遞檔案的原始內容

1$photo = fopen('photo.jpg', 'r');
2 
3$response = Http::attach(
4 'attachment', $photo, 'photo.jpg'
5)->post('http://example.com/attachments');

標頭

可以使用 withHeaders 方法將標頭新增至請求。此 withHeaders 方法接受索引鍵/值組的陣列

1$response = Http::withHeaders([
2 'X-First' => 'foo',
3 'X-Second' => 'bar'
4])->post('http://example.com/users', [
5 'name' => 'Taylor',
6]);

您可以使用 accept 方法指定您的應用程式在回應您的請求時預期的內容類型

1$response = Http::accept('application/json')->get('http://example.com/users');

為了方便起見,您可以使用 acceptJson 方法快速指定您的應用程式預期在回應您的請求時使用 application/json 內容類型

1$response = Http::acceptJson()->get('http://example.com/users');

withHeaders 方法會將新的標頭合併到請求的現有標頭中。如果需要,您可以使用 replaceHeaders 方法完全取代所有標頭

1$response = Http::withHeaders([
2 'X-Original' => 'foo',
3])->replaceHeaders([
4 'X-Replacement' => 'bar',
5])->post('http://example.com/users', [
6 'name' => 'Taylor',
7]);

身份驗證

您可以使用 withBasicAuthwithDigestAuth 方法分別指定基本和摘要驗證憑證

1// Basic authentication...
2$response = Http::withBasicAuth('[email protected]', 'secret')->post(/* ... */);
3 
4// Digest authentication...
5$response = Http::withDigestAuth('[email protected]', 'secret')->post(/* ... */);

Bearer 權杖

如果您想要快速將 bearer 權杖新增至請求的 Authorization 標頭,您可以使用 withToken 方法

1$response = Http::withToken('token')->post(/* ... */);

逾時

timeout 方法可用於指定等待回應的最長時間(以秒為單位)。依預設,HTTP 用戶端將在 30 秒後逾時

1$response = Http::timeout(3)->get(/* ... */);

如果超過給定的逾時時間,將會擲回 Illuminate\Http\Client\ConnectionException 的實例。

您可以使用 connectTimeout 方法指定嘗試連線到伺服器時等待的最長時間(以秒為單位)

1$response = Http::connectTimeout(3)->get(/* ... */);

重試

如果您希望 HTTP 用戶端在發生用戶端或伺服器錯誤時自動重試請求,您可以使用 retry 方法。retry 方法接受請求應嘗試的最大次數以及 Laravel 在嘗試之間應等待的毫秒數

1$response = Http::retry(3, 100)->post(/* ... */);

如果您想要手動計算嘗試之間要睡眠的毫秒數,您可以將閉包作為第二個引數傳遞給 retry 方法

1use Exception;
2 
3$response = Http::retry(3, function (int $attempt, Exception $exception) {
4 return $attempt * 100;
5})->post(/* ... */);

為了方便起見,您也可以提供陣列作為 retry 方法的第一個引數。此陣列將用於判斷後續嘗試之間要睡眠的毫秒數

1$response = Http::retry([100, 200])->post(/* ... */);

如果需要,您可以將第三個引數傳遞給 retry 方法。第三個引數應該是可呼叫的,它決定是否應實際嘗試重試。例如,您可能希望僅在初始請求遇到 ConnectionException 時重試請求

1use Exception;
2use Illuminate\Http\Client\PendingRequest;
3 
4$response = Http::retry(3, 100, function (Exception $exception, PendingRequest $request) {
5 return $exception instanceof ConnectionException;
6})->post(/* ... */);

如果請求嘗試失敗,您可能希望在進行新的嘗試之前對請求進行變更。您可以透過修改提供給您提供給 retry 方法的可呼叫物件的請求引數來達成此目的。例如,如果第一次嘗試傳回驗證錯誤,您可能想要使用新的授權權杖重試請求

1use Exception;
2use Illuminate\Http\Client\PendingRequest;
3use Illuminate\Http\Client\RequestException;
4 
5$response = Http::withToken($this->getToken())->retry(2, 0, function (Exception $exception, PendingRequest $request) {
6 if (! $exception instanceof RequestException || $exception->response->status() !== 401) {
7 return false;
8 }
9 
10 $request->withToken($this->getNewToken());
11 
12 return true;
13})->post(/* ... */);

如果所有請求都失敗,將會擲回 Illuminate\Http\Client\RequestException 的實例。如果您想要停用此行為,您可以提供 throw 引數,其值為 false。停用時,用戶端收到的最後一個回應將在嘗試所有重試後傳回

1$response = Http::retry(3, 100, throw: false)->post(/* ... */);

如果所有請求都因連線問題而失敗,即使 throw 引數設定為 false,仍會擲回 Illuminate\Http\Client\ConnectionException

錯誤處理

與 Guzzle 的預設行為不同,Laravel 的 HTTP 用戶端封裝不會在用戶端或伺服器錯誤(來自伺服器的 400500 層級回應)時擲回例外。您可以使用 successfulclientErrorserverError 方法判斷是否傳回了其中一個錯誤

1// Determine if the status code is >= 200 and < 300...
2$response->successful();
3 
4// Determine if the status code is >= 400...
5$response->failed();
6 
7// Determine if the response has a 400 level status code...
8$response->clientError();
9 
10// Determine if the response has a 500 level status code...
11$response->serverError();
12 
13// Immediately execute the given callback if there was a client or server error...
14$response->onError(callable $callback);

擲回例外

如果您有回應實例,並且想要在回應狀態碼指示用戶端或伺服器錯誤時擲回 Illuminate\Http\Client\RequestException 的實例,您可以使用 throwthrowIf 方法

1use Illuminate\Http\Client\Response;
2 
3$response = Http::post(/* ... */);
4 
5// Throw an exception if a client or server error occurred...
6$response->throw();
7 
8// Throw an exception if an error occurred and the given condition is true...
9$response->throwIf($condition);
10 
11// Throw an exception if an error occurred and the given closure resolves to true...
12$response->throwIf(fn (Response $response) => true);
13 
14// Throw an exception if an error occurred and the given condition is false...
15$response->throwUnless($condition);
16 
17// Throw an exception if an error occurred and the given closure resolves to false...
18$response->throwUnless(fn (Response $response) => false);
19 
20// Throw an exception if the response has a specific status code...
21$response->throwIfStatus(403);
22 
23// Throw an exception unless the response has a specific status code...
24$response->throwUnlessStatus(200);
25 
26return $response['user']['id'];

Illuminate\Http\Client\RequestException 實例具有公用 $response 屬性,可讓您檢查傳回的回應。

如果沒有發生錯誤,throw 方法會傳回回應實例,讓您可以將其他作業鏈結到 throw 方法

1return Http::post(/* ... */)->throw()->json();

如果您想要在擲回例外之前執行一些額外的邏輯,您可以將閉包傳遞給 throw 方法。例外將在叫用閉包後自動擲回,因此您不需要從閉包內重新擲回例外

1use Illuminate\Http\Client\Response;
2use Illuminate\Http\Client\RequestException;
3 
4return Http::post(/* ... */)->throw(function (Response $response, RequestException $e) {
5 // ...
6})->json();

依預設,在記錄或報告時,RequestException 訊息會截斷為 120 個字元。若要自訂或停用此行為,您可以在 bootstrap/app.php 檔案中設定應用程式的例外處理行為時,使用 truncateRequestExceptionsAtdontTruncateRequestExceptions 方法

1->withExceptions(function (Exceptions $exceptions) {
2 // Truncate request exception messages to 240 characters...
3 $exceptions->truncateRequestExceptionsAt(240);
4 
5 // Disable request exception message truncation...
6 $exceptions->dontTruncateRequestExceptions();
7})

Guzzle 中介層

由於 Laravel 的 HTTP 用戶端由 Guzzle 提供支援,因此您可以利用 Guzzle 中介層 來操作外送請求或檢查傳入回應。若要操作外送請求,請透過 withRequestMiddleware 方法註冊 Guzzle 中介層

1use Illuminate\Support\Facades\Http;
2use Psr\Http\Message\RequestInterface;
3 
4$response = Http::withRequestMiddleware(
5 function (RequestInterface $request) {
6 return $request->withHeader('X-Example', 'Value');
7 }
8)->get('http://example.com');

同樣地,您可以透過 withResponseMiddleware 方法註冊中介層來檢查傳入 HTTP 回應

1use Illuminate\Support\Facades\Http;
2use Psr\Http\Message\ResponseInterface;
3 
4$response = Http::withResponseMiddleware(
5 function (ResponseInterface $response) {
6 $header = $response->getHeader('X-Example');
7 
8 // ...
9 
10 return $response;
11 }
12)->get('http://example.com');

全域中介層

有時,您可能想要註冊一個中介層,該中介層適用於每個外送請求和傳入回應。若要達成此目的,您可以使用 globalRequestMiddlewareglobalResponseMiddleware 方法。通常,這些方法應在應用程式 AppServiceProviderboot 方法中叫用

1use Illuminate\Support\Facades\Http;
2 
3Http::globalRequestMiddleware(fn ($request) => $request->withHeader(
4 'User-Agent', 'Example Application/1.0'
5));
6 
7Http::globalResponseMiddleware(fn ($response) => $response->withHeader(
8 'X-Finished-At', now()->toDateTimeString()
9));

Guzzle 選項

您可以使用 withOptions 方法為外送請求指定其他 Guzzle 請求選項withOptions 方法接受索引鍵/值組的陣列

1$response = Http::withOptions([
2 'debug' => true,
3])->get('http://example.com/users');

全域選項

若要為每個外送請求設定預設選項,您可以使用 globalOptions 方法。通常,此方法應從應用程式 AppServiceProviderboot 方法中叫用

1use Illuminate\Support\Facades\Http;
2 
3/**
4 * Bootstrap any application services.
5 */
6public function boot(): void
7{
8 Http::globalOptions([
9 'allow_redirects' => false,
10 ]);
11}

並行請求

有時,您可能希望同時發出多個 HTTP 請求。換句話說,您希望同時分派多個請求,而不是循序發出請求。當與速度較慢的 HTTP API 互動時,這可以帶來顯著的效能提升。

值得慶幸的是,您可以使用 pool 方法來達成此目的。pool 方法接受一個閉包,該閉包會接收 Illuminate\Http\Client\Pool 實例,讓您可以輕鬆地將請求新增至請求池以進行分派

1use Illuminate\Http\Client\Pool;
2use Illuminate\Support\Facades\Http;
3 
4$responses = Http::pool(fn (Pool $pool) => [
5 $pool->get('https://127.0.0.1/first'),
6 $pool->get('https://127.0.0.1/second'),
7 $pool->get('https://127.0.0.1/third'),
8]);
9 
10return $responses[0]->ok() &&
11 $responses[1]->ok() &&
12 $responses[2]->ok();

如您所見,每個回應實例都可以根據新增至池的順序存取。如果您願意,可以使用 as 方法命名請求,這可讓您依名稱存取對應的回應

1use Illuminate\Http\Client\Pool;
2use Illuminate\Support\Facades\Http;
3 
4$responses = Http::pool(fn (Pool $pool) => [
5 $pool->as('first')->get('https://127.0.0.1/first'),
6 $pool->as('second')->get('https://127.0.0.1/second'),
7 $pool->as('third')->get('https://127.0.0.1/third'),
8]);
9 
10return $responses['first']->ok();

自訂並行請求

pool 方法無法與其他 HTTP 用戶端方法(例如 withHeadersmiddleware 方法)鏈結。如果您想要將自訂標頭或中介層套用至池化請求,您應該在池中的每個請求上設定這些選項

1use Illuminate\Http\Client\Pool;
2use Illuminate\Support\Facades\Http;
3 
4$headers = [
5 'X-Example' => 'example',
6];
7 
8$responses = Http::pool(fn (Pool $pool) => [
9 $pool->withHeaders($headers)->get('http://laravel.test/test'),
10 $pool->withHeaders($headers)->get('http://laravel.test/test'),
11 $pool->withHeaders($headers)->get('http://laravel.test/test'),
12]);

巨集

Laravel HTTP 用戶端可讓您定義「巨集」,巨集可以作為流暢、富有表現力的機制,在與應用程式中的服務互動時設定常見的請求路徑和標頭。若要開始使用,您可以在應用程式 App\Providers\AppServiceProvider 類別的 boot 方法中定義巨集

1use Illuminate\Support\Facades\Http;
2 
3/**
4 * Bootstrap any application services.
5 */
6public function boot(): void
7{
8 Http::macro('github', function () {
9 return Http::withHeaders([
10 'X-Example' => 'example',
11 ])->baseUrl('https://github.com');
12 });
13}

設定巨集後,您可以從應用程式中的任何位置叫用它,以建立具有指定組態的擱置請求

1$response = Http::github()->get('/');

測試

許多 Laravel 服務都提供功能來協助您輕鬆且富有表現力地編寫測試,而 Laravel 的 HTTP 用戶端也不例外。Http facade 的 fake 方法可讓您指示 HTTP 用戶端在發出請求時傳回 Stubbed / 虛擬回應。

偽造回應

例如,若要指示 HTTP 用戶端為每個請求傳回空的 200 狀態碼回應,您可以呼叫不帶引數的 fake 方法

1use Illuminate\Support\Facades\Http;
2 
3Http::fake();
4 
5$response = Http::post(/* ... */);

偽造特定 URL

或者,您可以將陣列傳遞給 fake 方法。陣列的索引鍵應代表您想要偽造的 URL 模式及其關聯的回應。* 字元可以用作萬用字元。對未偽造的 URL 發出的任何請求實際上都會執行。您可以使用 Http facade 的 response 方法為這些端點建構 Stub / 虛假回應

1Http::fake([
2 // Stub a JSON response for GitHub endpoints...
3 'github.com/*' => Http::response(['foo' => 'bar'], 200, $headers),
4 
5 // Stub a string response for Google endpoints...
6 'google.com/*' => Http::response('Hello World', 200, $headers),
7]);

如果您想要指定將 Stubbed 所有不符 URL 的後備 URL 模式,您可以使用單個 * 字元

1Http::fake([
2 // Stub a JSON response for GitHub endpoints...
3 'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']),
4 
5 // Stub a string response for all other endpoints...
6 '*' => Http::response('Hello World', 200, ['Headers']),
7]);

為了方便起見,可以透過提供字串、陣列或整數作為回應來產生簡單的字串、JSON 和空回應

1Http::fake([
2 'google.com/*' => 'Hello World',
3 'github.com/*' => ['foo' => 'bar'],
4 'chatgpt.com/*' => 200,
5]);

偽造連線例外

有時,您可能需要測試應用程式的行為,如果 HTTP 用戶端在嘗試發出請求時遇到 Illuminate\Http\Client\ConnectionException。您可以使用 failedConnection 方法指示 HTTP 用戶端擲回連線例外

1Http::fake([
2 'github.com/*' => Http::failedConnection(),
3]);

偽造回應序列

有時,您可能需要指定單個 URL 應依特定順序傳回一系列偽造回應。您可以使用 Http::sequence 方法來建構回應,以達成此目的

1Http::fake([
2 // Stub a series of responses for GitHub endpoints...
3 'github.com/*' => Http::sequence()
4 ->push('Hello World', 200)
5 ->push(['foo' => 'bar'], 200)
6 ->pushStatus(404),
7]);

當回應序列中的所有回應都已耗用時,任何進一步的請求都會導致回應序列擲回例外。如果您想要指定在序列為空時應傳回的預設回應,您可以使用 whenEmpty 方法

1Http::fake([
2 // Stub a series of responses for GitHub endpoints...
3 'github.com/*' => Http::sequence()
4 ->push('Hello World', 200)
5 ->push(['foo' => 'bar'], 200)
6 ->whenEmpty(Http::response()),
7]);

如果您想要偽造回應序列,但不需要指定應偽造的特定 URL 模式,您可以使用 Http::fakeSequence 方法

1Http::fakeSequence()
2 ->push('Hello World', 200)
3 ->whenEmpty(Http::response());

偽造回呼

如果您需要更複雜的邏輯來判斷要為特定端點傳回哪些回應,您可以將閉包傳遞給 fake 方法。此閉包將接收 Illuminate\Http\Client\Request 的實例,並應傳回回應實例。在您的閉包中,您可以執行判斷要傳回的回應類型所需的任何邏輯

1use Illuminate\Http\Client\Request;
2 
3Http::fake(function (Request $request) {
4 return Http::response('Hello World', 200);
5});

防止意外請求

如果您想要確保透過 HTTP 用戶端傳送的所有請求都在您的個別測試或完整測試套件中被偽造,您可以呼叫 preventStrayRequests 方法。在呼叫此方法之後,任何沒有對應偽造回應的請求都會擲回例外,而不是發出實際的 HTTP 請求

1use Illuminate\Support\Facades\Http;
2 
3Http::preventStrayRequests();
4 
5Http::fake([
6 'github.com/*' => Http::response('ok'),
7]);
8 
9// An "ok" response is returned...
10Http::get('https://github.com/laravel/framework');
11 
12// An exception is thrown...
13Http::get('https://laravel.dev.org.tw');

檢查請求

偽造回應時,您有時可能希望檢查用戶端接收到的請求,以確保您的應用程式傳送的是正確的資料或標頭。您可以透過在呼叫 Http::fake 後呼叫 Http::assertSent 方法來達成此目的。

assertSent 方法接受一個閉包,該閉包將接收 Illuminate\Http\Client\Request 實例,並應傳回布林值,指出請求是否符合您的預期。為了讓測試通過,至少必須發出一個符合給定預期的請求

1use Illuminate\Http\Client\Request;
2use Illuminate\Support\Facades\Http;
3 
4Http::fake();
5 
6Http::withHeaders([
7 'X-First' => 'foo',
8])->post('http://example.com/users', [
9 'name' => 'Taylor',
10 'role' => 'Developer',
11]);
12 
13Http::assertSent(function (Request $request) {
14 return $request->hasHeader('X-First', 'foo') &&
15 $request->url() == 'http://example.com/users' &&
16 $request['name'] == 'Taylor' &&
17 $request['role'] == 'Developer';
18});

如果需要,您可以使用 assertNotSent 方法斷言未傳送特定請求

1use Illuminate\Http\Client\Request;
2use Illuminate\Support\Facades\Http;
3 
4Http::fake();
5 
6Http::post('http://example.com/users', [
7 'name' => 'Taylor',
8 'role' => 'Developer',
9]);
10 
11Http::assertNotSent(function (Request $request) {
12 return $request->url() === 'http://example.com/posts';
13});

您可以使用 assertSentCount 方法斷言在測試期間「傳送」了多少個請求

1Http::fake();
2 
3Http::assertSentCount(5);

或者,您可以使用 assertNothingSent 方法斷言在測試期間未傳送任何請求

1Http::fake();
2 
3Http::assertNothingSent();

記錄請求/回應

您可以使用 recorded 方法收集所有請求及其對應的回應。recorded 方法會傳回陣列的集合,其中包含 Illuminate\Http\Client\RequestIlluminate\Http\Client\Response 的實例

1Http::fake([
2 'https://laravel.dev.org.tw' => Http::response(status: 500),
3 'https://nova.laravel.com/' => Http::response(),
4]);
5 
6Http::get('https://laravel.dev.org.tw');
7Http::get('https://nova.laravel.com/');
8 
9$recorded = Http::recorded();
10 
11[$request, $response] = $recorded[0];

此外,recorded 方法接受一個閉包,該閉包將接收 Illuminate\Http\Client\RequestIlluminate\Http\Client\Response 的實例,並且可以用於根據您的預期篩選請求/回應組

1use Illuminate\Http\Client\Request;
2use Illuminate\Http\Client\Response;
3 
4Http::fake([
5 'https://laravel.dev.org.tw' => Http::response(status: 500),
6 'https://nova.laravel.com/' => Http::response(),
7]);
8 
9Http::get('https://laravel.dev.org.tw');
10Http::get('https://nova.laravel.com/');
11 
12$recorded = Http::recorded(function (Request $request, Response $response) {
13 return $request->url() !== 'https://laravel.dev.org.tw' &&
14 $response->successful();
15});

事件

Laravel 在傳送 HTTP 請求的過程中會觸發三個事件。RequestSending 事件在傳送請求之前觸發,而 ResponseReceived 事件在收到給定請求的回應後觸發。如果未收到給定請求的回應,則會觸發 ConnectionFailed 事件。

RequestSendingConnectionFailed 事件都包含一個公用 $request 屬性,您可以使用該屬性來檢查 Illuminate\Http\Client\Request 實例。同樣地,ResponseReceived 事件包含 $request 屬性和 $response 屬性,可用於檢查 Illuminate\Http\Client\Response 實例。您可以在應用程式中為這些事件建立事件監聽器

1use Illuminate\Http\Client\Events\RequestSending;
2 
3class LogRequest
4{
5 /**
6 * Handle the given event.
7 */
8 public function handle(RequestSending $event): void
9 {
10 // $event->request ...
11 }
12}