Home >Backend Development >PHP Tutorial >Request Data Collection Handling using Laravel

Request Data Collection Handling using Laravel

Emily Anne Brown
Emily Anne BrownOriginal
2025-03-05 15:48:11225browse

Request Data Collection Handling using Laravel

Laravel's request->collect() method transforms input data into collections, enabling powerful data manipulation using Laravel's collection methods. This approach simplifies input processing and validation workflows.

<!-- Syntax highlighted by torchlight.dev -->// Basic usage
$input = $request->collect();
$filtered = $input->filter()->map(...);

Here's an example of an order processing system with complex input handling:

<!-- Syntax highlighted by torchlight.dev --><?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function bulkProcess(Request $request)
    {
        $result = $request->collect()
            ->reject(fn($item) => empty($item['product_id']))
            ->map(function ($item) {
                return [
                    'product_id' => $item['product_id'],
                    'quantity' => max(1, (int) $item['quantity']),
                    'price' => $this->calculatePrice($item),
                    'processed_at' => now()
                ];
            })
            ->groupBy('product_id')
            ->map(function ($group) {
                return [
                    'total_quantity' => $group->sum('quantity'),
                    'total_value' => $group->sum('price'),
                    'items' => $group->values()
                ];
            });

        return response()->json([
            'processed' => $result->count(),
            'summary' => $result
        ]);
    }

    private function calculatePrice($item): float
    {
        $basePrice = Product::find($item['product_id'])->price;
        return $basePrice * $item['quantity'];
    }
}

The request->collect() method streamlines input processing by providing access to Laravel's collection methods, making complex data transformations more readable and maintainable.

The above is the detailed content of Request Data Collection Handling using Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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