php
30 lines · 5 steps
Handling receipt uploads in a Laravel controller
A controller action that authorizes, validates, stores files privately, and persists each as a related record.
Explained by
highlit
1class OrderReceiptController extends Controller
2{
3 public function store(Request $request, Order $order)
4 {
5 $this->authorize('update', $order);
6
7 $validated = $request->validate([
8 'receipts' => ['required', 'array', 'max:10'],
9 'receipts.*' => ['file', 'mimes:jpg,jpeg,png,pdf', 'max:5120'],
10 ]);
11
12 $receipts = collect($validated['receipts'])->map(function ($file) use ($order) {
13 $path = $file->store("orders/{$order->id}/receipts", 'private');
14
15 return $order->receipts()->create([
16 'disk' => 'private',
17 'path' => $path,
18 'original_name' => $file->getClientOriginalName(),
19 'mime_type' => $file->getMimeType(),
20 'size' => $file->getSize(),
21 'uploaded_by' => $request->user()->id,
22 ]);
23 });
24
25 return response()->json([
26 'message' => 'Receipts attached successfully.',
27 'data' => ReceiptResource::collection($receipts),
28 ], Response::HTTP_CREATED);
29 }
30}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Authorize before you validate so unauthorized users never reach the work.
- 2Storing files and creating their metadata records together keeps uploads and database rows in sync.
- 3API Resources give you a consistent, controlled JSON shape for the response.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/handling-receipt-uploads-in-a-laravel-controller-explained-php-85f4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.