Hari ini, saya kongsikan kepada semua orang , cara membuat panggilan berbilang api dalam Laravel
Kami kini berjanji boleh memanggil berbilang api daripada klien (vue, react, js,...). jika anda menggunakan Promise.all([...]), ia mengembalikan berbilang janji
Baiklah, mari pergi
Yang pertama, anda boleh memasang projek Laravel 11
Yang kedua, kita boleh menyediakannya dalam web.php atau pengawal, perkhidmatan,..
Contoh : Saya menulis kod dalam fail web.php, bantu mengujinya
use Illuminate\Support\Facades\Http; use GuzzleHttp\Promise\Utils; use GuzzleHttp\Exception\ConnectException; use Illuminate\Http\Client\Pool; Route::get('multiple-request', function() { $responses = Utils::all([ 'foo' => Http::async()->get('https://jsonplaceholder.typicode.com/todos/1')->then(function ($response) { // you can check data, after then return it return $response; }), 'bar' => Http::async()->get('https://jsonplaceholder.typicode.com/todos/2')->then(function ($response) { // you can check data, after then return it return $response; }), 'baz' => Http::async()->get('https://jsonplaceholder.typicode.com/todos/3')->then(function ($response) { // you can check data, after then return it return $response; }), ])->wait(); // you need check data here $fooOk = $responses['foo']->ok(); $barSuccessful = $responses['bar']->successful(); $connectionFailed = $responses['baz'] instanceof ConnectException; return [ 'foo' => $responses['foo']->ok() ? $responses['foo']->json() : 'Request to foo failed', 'bar' => $responses['bar']->successful() ? $responses['bar']->json() : 'Request to bar failed', 'baz' => $responses['baz']->ok() ? $responses['baz']->json() : 'Request to baz failed', ]; });
Apabila anda meminta url : http://127.0.0.1/multiple-request , ia mengembalikan data
Baiklah, atau anda boleh menggunakan Http::pool , minta api
Route::get('multiple-request-using-pool', function() { $responses = Http::pool(fn (Pool $pool) => [ $pool->get('https://jsonplaceholder.typicode.com/todos/1'), $pool->get('https://jsonplaceholder.typicode.com/todos/2'), $pool->get('https://jsonplaceholder.typicode.com/todos/3'), ]); $responses[0]->ok(); $responses[1]->successful(); // Kiểm tra và lấy nội dung từ các phản hồi $data = [ 'todo_1' => $responses[0]->ok() ? $responses[0]->json() : 'Request to todo 1 failed', 'todo_2' => $responses[1]->successful() ? $responses[1]->json() : 'Request to todo 2 failed', 'todo_3' => $responses[2]->ok() ? $responses[2]->json() : 'Request to todo 3 failed', ]; return response()->json($data); });
Data pulangan :
Artikel : API Berbilang dalam Laravel dengan Permintaan HTTP
Atas ialah kandungan terperinci Berbilang API dalam Laravel dengan Permintaan HTTP. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!