Pattern Playbook

Advanced Laravel 13 and PHP 8.4, in 7 days

One rental platform, 54 production incidents

Follow Nordic Stays, a vacation-rental property management system, from its first booking to its busiest day. Every scene starts with something breaking in production. You read the broken code, fix it the way a senior Laravel team would, and see the design pattern, the framework internals and the scaling lesson behind the fix.

Start here

1. The incidentThe message the team got: a guest, finance, a partner, an alert.
2. The broken codeThe few lines that caused it, and why.
3. The fixProduction code, a short “why” on every important line.
4. The nameThe pattern you just wrote, how Laravel uses it, then the tests, folded.

The story

Two to four hours of careful reading a day, tests not included; about twice that if you type and run the code. 49 of 49 scenes are published. You should already know Laravel.

0FoundationThe app every scene starts from: setup, the core tables, models, factories and test helpersRead

Day 1Launch weekabout 2 h 10 min

Launch week. The first guests book and pay. Money, dates, the booking endpoint, double bookings, Stripe.

  1. 138 bookings, one cent short eachMoney in cents, Currency, Eloquent casts, CarbonImmutableValue Object25 min
  2. 2Every stay billed one night shortStay as calendar dates, nights, dates vs moments, property timezonesValue Object20 min
  3. 3500 error, and a stranger booked our cabinForm Request, Policy, action, Resource; 201, 403, 409, 422; the two trap testsActive Record25 min
  4. 4Two guests, same night, same secondTransactions, lockForUpdate(), Cache::lock(), why SQLite hides the bug, a real concurrency test10 min
  5. 5Our test suite created 312 payments in live StripeBindings, autowiring, register() vs boot(), swapping a service in testsSingletonDependency Injection Container25 min
  6. 6Marked paid by hand, but the guest never heardOne entry point for confirming a booking; Laravel facades inside; how fakes swap the real objectFacade25 min

Day 2Money comes inabout 3 h 5 min

Six weeks in. Quotes, Stripe webhooks, the booking lifecycle, refunds, reports and reconciliation.

  1. 7The quote said €1,098.90, the card was charged €1,105.50One price built step by step: nights, discount, fee, tax; percentages in basis points; line itemsBuilder45 min
  2. 8Stripe said paid, the booking is still pendingWebhooks: verify the signature, store, answer 200, process in a job; createOrFirst(); typed eventsSimple Factory30 min
  3. 9She paid two minutes after her hold expiredThe booking lifecycle as states, holds that expire on a schedule, late payments, refunds with Idempotency-KeyState50 min
  4. 10Refunded 100% on a strict bookingCancellation policies as classes, partial refunds after commit, bookings with no policyStrategyNull Object35 min
  5. 11Stripe and our books disagree by €40Nightly reconciliation: Stripe’s pages and our table as iterators, a comparing generator, lazyById() vs cursor()IteratorGenerator25 min

Day 3Channelsabout 4 h 5 min

Five months in. Airbnb and Booking.com: iCal, real APIs, rate limits, queues and overbookings.

  1. 12Two families, one cabin, one nightiCal sync: match by UID, updateOrCreate, deletes scoped to the source, one transaction30 min
  2. 13Every Airbnb call has failed with 401 for an hourOne interface for every channel, an adapter each, Laravel’s Manager, OAuth token refresh under a lockAdapterManager / DriverFactory Method50 min
  3. 14A day of Booking.com reservations never arrivedOne kit per channel: API client, signature verifier and payload mapper built from that channel’s own configurationAbstract Factory45 min
  4. 15A cancellation arrived before the bookingVersioned upserts under a lock, tombstones, a polling fallback, recorded payloads with Http::fake()35 min
  5. 16Airbnb blocked us for an hourRetries only for real blips, a shared Redis rate limit, 429 and Retry-After, release() and retryUntil()Decorator30 min
  6. 17642 pushes queued in one minuteState instead of changes, one request per calendar, ShouldBeUniqueUntilProcessing, WithoutOverlapping, two Redis queues, Horizon, retry_after, the worker loopCommandCommand Bus35 min
  7. 18Same night sold on Airbnb and Booking.comOne coordinator for every calendar change: overbookings recorded and reported once, every channel updatedMediator20 min

Day 4Hosts and guestsabout 4 h 20 min

A year in. Teams and roles, automatic guest messages, notifications and changed dates.

  1. 19A host saw another host’s bookingsIDOR, queries that start from the account, policies with 404s, scoped exists rules, no mass assignment20 min
  2. 20The cleaner can see payoutsRoles and policies, Gate::before; follow-up: invitations with signed URLs, removing a member35 min
  3. 21Arrival message sent at 3 a.m.Message templates, send_at built in the property’s timezone, DST tests, a scheduler with chunkById(), the review request after check-out35 min
  4. 22Guest got the door code twiceAn atomic pending → sent claim; a BookingCancelled event with independent listenersObserverEvent Dispatcher20 min
  5. 23Dates changed, the payment failed, the booking is half-changedSnapshot before the change, restore exactly when the payment fails, messages rescheduledMemento50 min
  6. 24{guest_name} showed up literally in the emailA fixed list checked on save, escaping after Markdown, an encrypted door code only near arrival25 min
  7. 25SMS guests got an email insteadLaravel Notifications as a bridge, the guest’s chosen channel, custom SMS and WhatsApp channels, hosts’ choicesBridge1 h 15 min

Day 5Operations and pricingabout 3 h 35 min

A year and a half in. Cleaning between stays, rate plans, rules for single dates, search, live calendars and the guest inbox.

  1. 26The cleaner arrived while guests were still insideCleaning tasks that follow the calendar, start times in the property’s timezone, telling the cleaner35 min
  2. 27Summer prices ignored the weekend ruleRate plans with seasons and a weekend rule, each night priced on its own, the order rules apply in25 min
  3. 28Changed the copy’s prices, the original’s changed tooEloquent replicate(), shallow vs deep copies, what a copy must never take alongPrototype15 min
  4. 29A 1-night Booking.com stay on a 3-night-minimum cabinMinimum stay sent to the channels with availability, one rule check for every booking path25 min
  5. 30A Christmas minimum stay closed short stays all yearA calendar_days table for rules that apply to some dates only: a minimum stay per arrival date, read by bookings and pushed to every channel25 min
  6. 31Search said free, the booking said takenOne availability rule as an Eloquent scope, shared by search, bookings, date changes and moves; whereDoesntHave(); when SQL is enoughSpecification25 min
  7. 32The calendar didn’t update when Airbnb bookedReverb, broadcasting after commit, private channels scoped to the account, the socket as a hint and a reload after reconnect25 min
  8. 33Two co-hosts sent the same guest different check-in timesA presence channel per conversation, who else is answering, typing whispers, channel auth scoped to the account40 min

Day 6Scaleabout 3 h 25 min

Three years in: 21,000 properties and two million bookings. Slow pages, caching and Redis, an outbox, safe retries, a partner API with versions and scoped tokens, and exports.

  1. 34The properties page takes 4 secondsN+1 queries, eager loading with constraints, withCount() and ofMany(), why lazy-loading protection missed it, EXPLAIN20 min
  2. 35Prices went up at 09:00, guests paid the old ones until 10:00A caching proxy, versioned keys bumped after commit, never caching the price a guest pays, cache-aside; follow-up: Redis eviction policies and separate connectionsProxy45 min
  3. 36Booking saved, the partner never heard about itWriting the message in the same transaction, a relay job, at-least-once delivery, idempotent consumers, event versionsTransactional Outbox40 min
  4. 37The mobile app retried and booked twiceAn Idempotency-Key middleware, how Laravel’s middleware pipeline works, replaying the stored responseChain of ResponsibilityPipeline20 min
  5. 38A partner’s nightly sync missed bookingsOffset vs cursor pagination, cursorPaginate(), whitelisted filters and sorts, a breaking change shipped as /api/v2, deprecating v120 min
  6. 39A channel manager cancelled 14 bookings with a host’s tokenSanctum token abilities on every route, expiry, a token bound to one account, a rate limit per token with 429 and Retry-After, JSON errors, and when OAuth with Passport is worth it25 min
  7. 40The tax report export included another host’s bookingsOne base class for every CSV export: the account scope, chunked reads and streamed downloads that no export can skipTemplate Method35 min

Day 7Productionabout 4 h

The following weeks. Syncs and deadlocks, the busiest day, CDN and stampedes, search and reindexing, big tables, deploys on two servers, an incident, the interview and a code review.

  1. 41iCal calendars are three hours out of dateChanges worked out in memory and written in one short transaction: upsert(), one delete, only real differences written; follow-up: deadlocks, REPEATABLE READ, gap and next-key locksUnit of Work30 min
  2. 42Busiest day of the year: search p99 is 8 secondsk6 at a fixed arrival rate, p95 and p99, EXPLAIN and a composite index, read replicas, sticky, what must read the primary; follow-up: Cache::flexible() against a stampede; and a CDN with Cache-Control, ETag and purging35 min
  3. 43Meilisearch restarted, search returned 500 for ten minutesScout and Meilisearch behind one search interface, the SQL search as a fallback, contract tests for both, the Eloquent repository debate; follow-up: an amenities filter (an enum: PHP’s own Flyweight) and reindexing without downtime by swapping indexesRepository55 min
  4. 44Adding a column locked bookings for 20 minutesMetadata locks, ALGORITHM=INSTANT and lock_wait_timeout, reports off the primary, batched backfills, gh-ost; follow-up: retention with MassPrunable, archiving, and why not partitioning25 min
  5. 45Deployed at 14:00, workers ran old code until 16:00Release directories and an atomic switch, OPcache, horizon:terminate, Supervisor, onOneServer() on two servers, CI, Octane; follow-up: Reverb on two servers through Redis20 min
  6. 46Stuck queue, a worker eating memoryLogs → metrics → reproduce → fix → postmortem; static state in workers, memory, maxJobs and maxTime, wait-time alerts20 min
  7. 47A new developer asks how it all fits togetherOne booking end to end, where code goes, the container inside, Pint, Larastan, arch tests, mutation testing, Rector, upgrades25 min
  8. 48The interviewSystem design of a channel manager: requirements, numbers, data model, flows, pushback, trade-offs; behavioural answers; the follow-up: sharding by account10 min
  9. 49Review this pull requestAn AI-written pull request with eight bugs: find them, explain them, fix them, and ask for the tests that prove it20 min

After Day 7Five patterns outside the story

Patterns a Laravel PMS doesn’t need, built for real on their own, so you know them when you meet them.

  1. +Five patterns outside the storyComposite, Data Mapper, Interpreter, Visitor and Flyweight, each built from scratch for a job where it fits, with testsCompositeData MapperInterpreterVisitorFlyweightRead