Laravel Tutorials

Request Data Collection Handling using Laravel

Published
Request Data Collection Handling using Laravel image

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.

// Basic usage
$input = $request->collect();
$filtered = $input->filter()->map(...);

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

<?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.

Harris Raftopoulos photo

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

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Slow Job Alerts and Replica Commit IDs in Laravel 13.40 image

Slow Job Alerts and Replica Commit IDs in Laravel 13.40

Read article
Flock: A Free, Native Herd Alternative for Laravel image

Flock: A Free, Native Herd Alternative for Laravel

Read article
Live Props for Real-Time Updates in Inertia.js v3.11 image

Live Props for Real-Time Updates in Inertia.js v3.11

Read article
Cooldown Dependency Policy now in Composer 2.11 image

Cooldown Dependency Policy now in Composer 2.11

Read article
Email Sending and Testing for Laravel in One Account image

Email Sending and Testing for Laravel in One Account

Read article
Decide with Jev: Tie Every AI Check to the Exact Draft image

Decide with Jev: Tie Every AI Check to the Exact Draft

Read article