Laravel Tutorials

Extracting Sequential Data with Laravel's takeWhile

Published Updated
Extracting Sequential Data with Laravel's takeWhile image

Laravel's takeWhile method provides precise control over collection filtering, allowing you to extract elements that consecutively meet a condition until the first failure occurs.

$numbers = collect([1, 2, 3, 4, 2, 1]);

$ascending = $numbers->takeWhile(function ($number, $key) use ($numbers) {
    if ($key === 0) return true;
    return $number > $numbers[$key - 1];
});
// Result: [1, 2, 3, 4]

Let's explore a practical example of managing an order processing system with status tracking:

<?php

namespace App\Services;

use App\Models\Order;
use App\Models\OrderStatus;
use Illuminate\Support\Collection;

class OrderProcessingService
{
    public function getSuccessfulSteps(Order $order): Collection
    {
        return $order->statusUpdates()
            ->oldest()
            ->get()
            ->takeWhile(function (OrderStatus $status) {
                return $status->successful;
            })
            ->map(function (OrderStatus $status) {
                return [
                    'step' => $status->step_name,
                    'completed_at' => $status->created_at->format('Y-m-d H:i:s'),
                    'processor' => $status->processor_name
                ];
            });
    }

    public function validateProcessingSequence(Collection $steps): bool
    {
        $requiredOrder = ['payment', 'inventory', 'packaging', 'shipping'];
        $currentStep = 0;

        return $steps->takeWhile(function ($step) use ($requiredOrder, &$currentStep) {
            return $step['type'] === $requiredOrder[$currentStep++] ?? null;
        })->count() === count($requiredOrder);
    }
}

TakeWhile offers a powerful way to work with sequential data, perfect for processing status updates, validating sequences, or analyzing trends in your data.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
Generate Laravel Validation Rules From a JSON Schema image

Generate Laravel Validation Rules From a JSON Schema

Read article
Laravel Suspicious Login: Detect and Block Risky Logins image

Laravel Suspicious Login: Detect and Block Risky Logins

Read article
Decide with Jev: Make Failed AI Requests Safe in Laravel image

Decide with Jev: Make Failed AI Requests Safe in Laravel

Read article
Black Friday: Learn the habits behind AI workflows that work image

Black Friday: Learn the habits behind AI workflows that work

Read article
Laravel Black Friday and Cyber Monday Deals 2026 image

Laravel Black Friday and Cyber Monday Deals 2026

Read article
pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux image

pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux

Read article