CodingTricks LogoCodingTricks
HomePostsTipsCopy/PasteLinksContact UsAbout Us
2024 - 2025 CodingTricks.co | All rights reserved
Privacy PolicyTerms of Service
Mastering Laravel Streamed Responses: Boost Performance with Fast Data Delivery

Mastering Laravel Streamed Responses: Boost Performance with Fast Data Delivery

Posted by

kamlesh paul

on

Apr 3, 2025

| 4 min read

Last updated on : Apr 13, 2025

Tips
1156 views

Sometimes you need to send data to users without making them wait a long time. Laravel’s new streamed response functions make this simple! They let you send stuff bit by bit, like watching a video while it downloads. Let’s check out what’s new: stream(), streamJson(), and eventStream().

#Table of contents

  • What’s This All About?
  • 1. stream(): Sending Anything in Chunks
    • How It Works
    • Quick Example
    • When to Use It
  • 2. streamJson(): JSON Without the Slowdown
    • How It Works
    • Quick Example
    • When to Use It
  • 3. eventStream(): Real-Time Updates
    • How It Works
    • Quick Example
    • When to Use It
  • Why Bother?
  • Wrap-Up

#What’s This All About?

Usually, when your app sends data, it waits until everything’s ready. That can take forever if the data’s big. Streamed responses fix that by sending small pieces as soon as they’re good to go. It’s faster, uses less memory, and feels smooth for users.

#1. stream(): Sending Anything in Chunks

The stream() function is for sending all kinds of data little by little. It’s great for big files or stuff that takes time to make.

#How It Works

You write a function that sends data in parts. Laravel pushes each part out right away if you use ob_flush() and flush().

#Quick Example

Here’s a route that sends “Hello, ” then waits a bit, and sends “World!”:

Route::get('/stream', function () {
    return response()->stream(function () {
        echo 'Hello, ';
        ob_flush();
        flush();
        sleep(2); // Fake some work
        echo 'World!';
        ob_flush();
        flush();
    }, 200, ['X-Accel-Buffering' => 'no']);
});

Hit that route, and you’ll see “Hello, ” first, then “World!” after 2 seconds. It’s a chill way to send stuff without loading everything at once.

Note: Make sure output_buffering is enabled in your PHP settings (e.g., output_buffering = 4096 in php.ini), or you might run into the error: ob_flush(): Failed to flush buffer. No buffer to flush.

#When to Use It

  • Big file downloads.
  • Data you build step by step, like logs.

#2. streamJson(): JSON Without the Slowdown

If your app sends a lot of JSON—like an API with tons of data—streamJson() is perfect. It sends JSON in pieces so the client gets it fast.

#How It Works

Give it an array or a lazy collection (like cursor() for database stuff), and it streams the JSON without choking your server.

#Quick Example

Here’s how to stream a list of users:

use App\Models\User;
 
Route::get('/users.json', function () {
    return response()->streamJson([
        'users' => User::cursor(), // Grabs users one at a time
    ]);
});

This keeps things quick even with thousands of users.

#When to Use It

  • Big JSON responses.
  • APIs where you don’t want to load everything in memory.

#3. eventStream(): Real-Time Updates

Want to send live updates, like a chat or notifications? eventStream() uses Server-Sent Events (SSE) to push stuff to the client right when it happens.

#How It Works

You send StreamedEvent objects with event names and data. The client listens with JavaScript, and Laravel closes the stream when you’re done.

#Quick Example

Here’s a chat stream:

use Illuminate\Http\StreamedEvent;
 
Route::get('/chat', function () {
    return response()->eventStream(function () {
        $stream = OpenAI::client()->chat()->createStreamed(...);
        foreach ($stream as $response) {
            yield new StreamedEvent(
                event: 'message',
                data: json_encode($response->choices[0])
            );
        }
    });
});

On the frontend, you’d grab it like this:

const source = new EventSource('/chat');
source.addEventListener('message', (event) => {
    console.log('New message:', event.data);
});

This keeps users updated without them refreshing.

#When to Use It

  • Chat apps or live notifications.
  • Dashboards with real-time numbers.

#Why Bother?

These streamed responses make your app better:

  • Less Memory: No need to hold everything at once.
  • Faster: Users get data sooner.
  • Live Stuff: Updates happen instantly with eventStream().

It’s all about keeping things smooth and quick.

#Wrap-Up

Laravel’s streamed responses—stream(), streamJson(), and eventStream()—are easy tools to send data smarter. Use stream() for anything chunky, streamJson() for big JSON, and eventStream() for live updates. Pick what fits your project and watch your app speed up!

Related Posts

  • Blocking Disposable Emails with the laravel-disposable-email PackageBlocking Disposable Emails with the laravel-disposable-email Package
  • NextJS App Router SEO Best PracticesNextJS App Router SEO Best Practices
  • How to Personalize Visual Studio Code (VSCode)How to Personalize Visual Studio Code (VSCode)
  • Email Testing with Mailtrap in NextJSEmail Testing with Mailtrap in NextJS
  • A Nice Way to Handle React Server Actions with react-hot-toastA Nice Way to Handle React Server Actions with react-hot-toast

Tags

Api(1)Authentication(5)Backup (1)Copy Paste(12)Email(2)Express(1)Firebase(1)Github Action(2)News(8)Push Notification(1)Queue(2)Server(11)Server Action(3)Testing(1)Tips(17)Websocket(1)

Popular Posts

  • TweakPHP 0.1.0 Beta: A Free and Open-Source Alternative to Tinkerwell Is Here!  TweakPHP 0.1.0 Beta: A Free and Open-Source Alternative to Tinkerwell Is Here!
  • How to use WebSocket in NextJS App router with Socket.IOHow to use WebSocket in NextJS App router with Socket.IO
  • How to Set Up Queue Jobs in NextJS Using BullMQHow to Set Up Queue Jobs in NextJS Using BullMQ
  • Boost Laravel Performance: Running Octane with FrankenPHP in Production ( Zero downtime)Boost Laravel Performance: Running Octane with FrankenPHP in Production ( Zero downtime)
  • How to Set Up NextJS cron jobs without VercelHow to Set Up NextJS cron jobs without Vercel
  • Mastering Laravel Streamed Responses: Boost Performance with Fast Data DeliveryMastering Laravel Streamed Responses: Boost Performance with Fast Data Delivery
  • Tinkerwell Alternative: Free and Open-Source PHP Debugging with TweakPHPTinkerwell Alternative: Free and Open-Source PHP Debugging with TweakPHP
  • Nextjs 14 roles and permissions (RBAC) : Step-by-Step GuideNextjs 14 roles and permissions (RBAC) : Step-by-Step Guide

Get updates directly to your inbox.

Join 500+ developers getting updates on Laravel & Next.js tips. No spam,
unsubscribe anytime.


Share this article:

1156 views