Home > Backend Development > PHP Tutorial > Extracting Sequential Data with Laravel's takeWhile

Extracting Sequential Data with Laravel's takeWhile

百草
Release: 2025-03-06 01:34:13
Original
833 people have browsed it

Extracting Sequential Data with Laravel's takeWhile

Laravel's takeWhile method offers precise control over collection filtering. It extracts consecutive elements satisfying a given condition, stopping at the first element that fails the condition.

This example demonstrates extracting ascending numbers from a collection:

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

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

Here's a practical application: tracking order processing status.

<?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(fn (OrderStatus $status) => $status->successful)
            ->map(fn (OrderStatus $status) => [
                '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(fn ($step) use ($requiredOrder, &$currentStep) => $step['type'] === ($requiredOrder[$currentStep++] ?? null))->count() === count($requiredOrder);
    }
}
Copy after login

takeWhile is ideal for handling sequential data, particularly useful for processing status updates, validating sequences, or analyzing data trends. The method provides a concise and efficient way to manage such scenarios.

The above is the detailed content of Extracting Sequential Data with Laravel's takeWhile. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template