Laravel Tip 💡📢 : Streamed JSON Responses Added to Laravel 10
Chúng ta hay sử dụng api trong các dự án vừa, nhỏ và lớn. Nhưng chúng ta sẽ biết một điều, nếu dữ liệu backend trả về số lượng lớn, thì sẽ làm cho api nó sẽ chạm đi rất nhiều, chính vì thế nay mình chia sẻ với mọi người cách sử dụng Streamed JSON Response được tích hợp trong Laravel 10.43
Cách sử dụng api trả về dữ liệu từng phần, sẽ làm cho api trả về sẽ nhẹ nhàng hơn rất nhiều, thay vì trả về một đóng dữ liệu json
Tìm hiểu thêm tại đây: https://symfony.com/doc/6.3/components/http_foundation.html#streaming-a-json-response
use Symfony\Component\HttpFoundation\StreamedResponse;
use Illuminate\Support\Facades\Http;
Route::get('/stream', function () {
// ✅ Chỉ chấp nhận dữ liệu dạng "json"
$responseJson = Http::acceptJson()->get('https://dummyjson.com/products')['products'];
// 📌 Cài đặt StreamedResponse để trả dữ liệu về từng phần
// ✅ Sử dụng khi dữ liệu trả về số lượng lớn
$response = new StreamedResponse(function () use ($responseJson) {
foreach ($responseJson as $key => $value) {
echo json_encode($value) . "\n";
}
}, 200, [
'Content-Type' => 'application/json',
]);
// 😁 return full data json
// return $responseJson;
return $response;
});
Danh sách Laravel Tip 💡📢 :