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 namespace App\Listeners;
How event subscribers group listeners in Laravel
event-driven
subscribers
queues
Intermediate
6 steps
php
<?php namespace App\Services;
How user impersonation works in Laravel
authentication
authorization
session
Intermediate
8 steps
go
package handlers import ( "net/http"
Custom validators and binding in Gin
validation
struct-tags
error-handling
Intermediate
8 steps
python
import secrets from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import APIKeyHeader
API key authentication as a FastAPI dependency
authentication
dependency-injection
api-keys
Intermediate
8 steps
javascript
function parseHexColor(hex) { const cleaned = hex.trim().replace(/^#/, ''); const expand = (short) =>
Parsing hex colors into RGBA channels
parsing
bitwise
regex
Intermediate
7 steps
php
<?php final class RememberMeCookie {
Signed remember-me cookies in PHP
authentication
hmac
cookies
Intermediate
8 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.