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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Authorize before you validate so unauthorized users never reach the work.
  2. 2Storing files and creating their metadata records together keeps uploads and database rows in sync.
  3. 3API Resources give you a consistent, controlled JSON shape for the response.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Handling receipt uploads in a Laravel controller — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code