Pattern Playbook

Course › Day 1 · Launch week › Scene 6 of 49 · 25 min

Marked paid by hand, but the guest never heard

One entry point for confirming a booking; Laravel facades inside; how fakes swap the real object

Facade

On this page
  1. The incident
  2. The broken code
  3. The fix: one front door
  4. The pattern
  5. Laravel facades are something else
  6. Tests
  7. Remember

#supportFriday 15:20

Mona · supportA host got a bank transfer for the Lake Cabin and clicked Mark as paid. The booking says *confirmed*, but finance still sees the payment as pending, and the guest never got a confirmation email. She’s asking if her booking is real.

The broken code

Confirming a booking is several steps. Each place that confirms one knows a different subset of them. The card payment’s return page:

app/Http/Controllers/PaymentReturnController.php (before)the bug
<?php

namespace App\Http\Controllers;

use App\Enums\BookingStatus;
use App\Enums\PaymentStatus;
use App\Mail\BookingConfirmedMail;
use App\Models\Payment;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class PaymentReturnController extends Controller
{
    // Stripe sends the guest's browser here after a card payment: /payments/return?payment_intent=pi_...
    public function __invoke(Request $request): View
    {
        $payment = Payment::where('provider_payment_id', $request->query('payment_intent'))->firstOrFail();
        $booking = $payment->booking;

        $booking->status = BookingStatus::Confirmed;                       // three steps, no transaction
        $booking->confirmed_at = now();
        $booking->save();
        $payment->update(['status' => PaymentStatus::Succeeded]);
        Mail::to($booking->guest_email)->send(new BookingConfirmedMail($booking));

        return view('bookings.thank-you');
    }
}

And the "Mark as paid" button for bank transfers, added later by someone else:

app/Http/Controllers/MarkBookingPaidController.php (before)the bug
<?php

namespace App\Http\Controllers;

use App\Enums\BookingStatus;
use App\Http\Resources\BookingResource;
use App\Models\Booking;

class MarkBookingPaidController extends Controller
{
    // The host received a bank transfer and clicks "Mark as paid"
    public function __invoke(Booking $booking): BookingResource
    {
        $booking->status = BookingStatus::Confirmed;                       // one step, written later by someone else
        $booking->save();

        return new BookingResource($booking);
    }
}

Nothing here is hard. The problem is that "confirm a booking" has no home, so every caller has to know all the steps, in the right order, inside a transaction. The next scenes add more steps (close the dates on Airbnb, schedule guest messages, plan the cleaning). Each one would have to be added to every caller, and one will always be forgotten.

How the fix works, in one picture

Before

card paymentreturn pageconfirm + emailbank transferMark as paidstatus onlyno payment, no email

Each door did its own subset of confirming, and the manual one skipped the payment and the email.

After

card paymentreturn pageBookingConfirmationbank transferMark as paidBookingConfirmationpayment, status, email: every time

Every door calls one confirmation, which always does every step.

The fix: one front door

The guest’s email

A queued notification, so a slow mail server never slows down the request. Guests aren’t users, so it is sent "on demand" to an address, below.

app/Notifications/BookingConfirmed.phpnew file
<?php

namespace App\Notifications;

use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class BookingConfirmed extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(public Booking $booking)
    {
    }

    /** @return list<string> */
    public function via(object $notifiable): array
    {
        return ['mail'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        $stay = $this->booking->stay;

        return (new MailMessage())
            ->subject("Your stay at {$this->booking->property->name} is confirmed")
            ->greeting("Hi {$this->booking->guest_name},")
            ->line("See you from {$stay->checkIn->toFormattedDateString()} to {$stay->checkOut->toFormattedDateString()}.")
            ->line("Total paid: {$this->booking->total->format()}");
    }
}

The facade

One public method that runs every step, in the right order. The status and the payment change in one transaction, so either both happen or neither does. The email is queued with afterCommit(): it only leaves once the transaction has committed, so a guest never gets an email for a change that was rolled back.

The booking row is locked (scene 4), so two confirmations at the same moment run one after the other, and the second one finds the booking already confirmed and does nothing.

app/Bookings/BookingConfirmation.phpnew file
<?php

namespace App\Bookings;

use App\Enums\BookingStatus;
use App\Enums\PaymentStatus;
use App\Models\Booking;
use App\Models\Payment;
use App\Notifications\BookingConfirmed;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Notification;
use LogicException;

final class BookingConfirmation
{
    public function confirm(Booking $booking, Payment $payment): void
    {
        DB::transaction(function () use ($booking, $payment): void {
            $booking = Booking::whereKey($booking->id)->lockForUpdate()->firstOrFail();   // fresh, and locked

            if ($booking->status === BookingStatus::Confirmed) {
                return;                                                // confirmed already: nothing to do
            }
            if ($booking->status !== BookingStatus::Pending) {
                throw new LogicException("Booking {$booking->id} is {$booking->status->value} and can't be confirmed.");
            }

            $booking->status = BookingStatus::Confirmed;               // step 1
            $booking->confirmed_at = now();
            $booking->expires_at = null;                               // no longer a hold
            $booking->save();

            $payment->status = PaymentStatus::Succeeded;               // step 2
            $payment->save();

            Notification::route('mail', $booking->guest_email)         // step 3, after the commit
                ->notify((new BookingConfirmed($booking))->afterCommit());

            // Day 3 adds: close the dates on every channel. Day 4: schedule guest messages. Day 5: plan the cleaning.
        });
    }
}

Every caller is now one line

The card payment and the bank transfer both go through the same door. When Day 3 adds "close the dates on Airbnb", it is added once, inside confirm(), and no caller changes. The container fills in BookingConfirmation $confirmation (scene 5).

app/Http/Controllers/PaymentReturnController.php (after)changed since the version above: +4 −12
<?php namespace App\Http\Controllers; use App\Enums\BookingStatus;use App\Enums\PaymentStatus;use App\Mail\BookingConfirmedMail;use App\Bookings\BookingConfirmation;use App\Models\Payment;use Illuminate\Contracts\View\View;use Illuminate\Http\Request;use Illuminate\Support\Facades\Mail; class PaymentReturnController extends Controller{    // Stripe sends the guest's browser here after a card payment: /payments/return?payment_intent=pi_...    public function __invoke(Request $request): View    public function __invoke(Request $request, BookingConfirmation $confirmation): View    {        $payment = Payment::where('provider_payment_id', $request->query('payment_intent'))->firstOrFail();        $booking = $payment->booking;         $booking->status = BookingStatus::Confirmed;                       // three steps, no transaction        $booking->confirmed_at = now();        $booking->save();        $payment->update(['status' => PaymentStatus::Succeeded]);        Mail::to($booking->guest_email)->send(new BookingConfirmedMail($booking));         $confirmation->confirm($payment->booking, $payment);              // every step, in one place         return view('bookings.thank-you');    }}

A bank transfer has no Stripe payment, so the controller records one first, then uses the same door:

app/Http/Controllers/MarkBookingPaidController.php (after)changed since the version above: +13 −7
<?php namespace App\Http\Controllers; use App\Enums\BookingStatus;use App\Bookings\BookingConfirmation;use App\Enums\PaymentStatus;use App\Http\Resources\BookingResource;use App\Models\Booking; class MarkBookingPaidController extends Controller{    // The host received a bank transfer and clicks "Mark as paid"    public function __invoke(Booking $booking): BookingResource    {        $booking->status = BookingStatus::Confirmed;                       // one step, written later by someone else        $booking->save();         return new BookingResource($booking);    public function __invoke(Booking $booking, BookingConfirmation $confirmation): BookingResource    {        $payment = $booking->payments()->create([                         // record the transfer first            'amount_cents' => $booking->total->amount,            'currency' => $booking->total->currency->value,            'status' => PaymentStatus::Pending,                            // no Stripe id: paid outside Stripe        ]);         $confirmation->confirm($booking, $payment);                        // then the same door as a card payment         return new BookingResource($booking->refresh());    }}

Who may press "Mark as paid" is a policy question; scenes 19 and 20 add it to this route.

Their routes

Both controllers have been routed since launch. Here are the two route files in full, so your app has them too. The API route:

routes/api.phpchanged since scene 5: +4
<?php use App\Http\Controllers\BookingController;use App\Http\Controllers\BookingPaymentController;use App\Http\Controllers\MarkBookingPaidController;use Illuminate\Support\Facades\Route; // Laravel serves this file under /api: the full URL is /api/v1/properties/{property}/bookings.Route::post('/v1/properties/{property}/bookings', [BookingController::class, 'store'])    ->middleware('auth:sanctum')    ->can('createBooking', 'property'); Route::post('/v1/bookings/{booking}/payment', BookingPaymentController::class)    ->middleware('auth:sanctum'); Route::post('/v1/bookings/{booking}/mark-paid', MarkBookingPaidController::class)    ->middleware('auth:sanctum');                                       // who may: scenes 19 and 20

The return page is a web route, because it is the guest’s browser that arrives there:

routes/web.phpnew file
<?php

use App\Http\Controllers\PaymentReturnController;
use Illuminate\Support\Facades\Route;

Route::get('/', fn () => view('welcome'));

// Stripe sends the guest's browser here after a card payment (the return_url of the payment).
Route::get('/payments/return', PaymentReturnController::class)->name('payments.return');

You just wrote the Facade pattern

FacadeOne simple entry point in front of a group of steps or classes, so callers don’t have to know how they fit together.

  • Callers know one method. The order of the steps, the transaction and the lock are the facade’s business.
  • Each step stays in its own place: the facade only coordinates. The email is in the notification; scene 9 moves the status rules into the booking’s states.
  • New steps are added in one place, and no caller changes.

When not to use it

  • Don’t let a facade grow rules of its own. It orders steps; if confirm() starts calculating refunds, it’s turning into a god class.
  • Don’t put a facade in front of a single step. One call needs no front door.

Laravel facades are something else

Notification::route(), DB::transaction() and Cache::get() are called "facades" in Laravel, but they aren’t the Facade pattern from this scene. A Laravel facade has no logic: it forwards every static call to one object in the container. That’s also why fakes work: put a different object in the container, and every static call reaches it.

Every static call is forwarded

Illuminate/Support/Facades/Facade.php (simplified)
public static function __callStatic($method, $args)
{
    $instance = static::getFacadeRoot();                     // the real object behind the facade

    if (! $instance) {
        throw new RuntimeException('A facade root has not been set.');
    }

    return $instance->$method(...$args);                     // Notification::route() → $channelManager->route()
}

protected static function resolveFacadeInstance($name)
{
    if (isset(static::$resolvedInstance[$name])) {
        return static::$resolvedInstance[$name];             // looked up once, then remembered
    }

    return static::$resolvedInstance[$name] = static::$app[$name];   // from the container
}

A fake is a swap

Notification::fake() builds a NotificationFake and swaps it in, both in the facade’s memory and in the container. From then on every notification lands in the fake, which records it instead of sending it.

Illuminate/Support/Facades/Facade.php (simplified)
public static function swap($instance)
{
    static::$resolvedInstance[static::getFacadeAccessor()] = $instance;

    if (isset(static::$app)) {
        static::$app->instance(static::getFacadeAccessor(), $instance);   // injected code gets the fake too
    }
}
The Facade patternLaravel facade
What it isA class that runs many steps behind one methodA static shortcut to one object in the container
Has logic?Yes: which steps, in which orderNo: it only forwards calls
HereBookingConfirmation::confirm()Notification::route(), DB::transaction()
TestsEvery step happens, once, and only for a pending booking
tests/Feature/BookingConfirmationTest.phpnew file
<?php

use App\Bookings\BookingConfirmation;
use App\Enums\BookingStatus;
use App\Enums\PaymentStatus;
use App\Models\Booking;
use App\Models\Payment;
use App\Notifications\BookingConfirmed;
use Illuminate\Support\Facades\Notification;

beforeEach(fn () => Notification::fake());

it('confirms the booking, marks the payment paid and emails the guest', function () {
    $booking = Booking::factory()->pending()->create(['guest_email' => 'mona@example.com']);
    $payment = Payment::factory()->for($booking)->create();

    app(BookingConfirmation::class)->confirm($booking, $payment);

    expect($booking->fresh())
        ->status->toBe(BookingStatus::Confirmed)
        ->confirmed_at->not->toBeNull()
        ->expires_at->toBeNull()
        ->and($payment->fresh()->status)->toBe(PaymentStatus::Succeeded);

    Notification::assertSentOnDemand(
        BookingConfirmed::class,
        fn (BookingConfirmed $notification, array $channels, object $notifiable): bool => $notifiable->routes['mail'] === 'mona@example.com',
    );
});

it('does nothing the second time', function () {
    $booking = Booking::factory()->pending()->create();
    $payment = Payment::factory()->for($booking)->create();

    app(BookingConfirmation::class)->confirm($booking, $payment);
    app(BookingConfirmation::class)->confirm($booking, $payment);

    Notification::assertSentOnDemandTimes(BookingConfirmed::class, 1);
});

it('refuses to confirm a cancelled booking', function () {
    $booking = Booking::factory()->cancelled()->create();

    app(BookingConfirmation::class)->confirm($booking, Payment::factory()->for($booking)->create());
})->throws(LogicException::class, 'cancelled');

Remember

  • One entry point for an outcome (confirming a booking), however many doors lead to it.
  • A Laravel facade is a static-looking call to an object in the container, which is why it can be faked.

Day 1 is done: money, dates, the endpoint, double bookings, payments and confirmation all have one home. Day 2 starts on Monday, when a guest is charged €6.60 more than her quote said.