Skip to content

Lesson 11 of 22 · Architecture and Code Organization

Laravel Traits for Business Rules

Intermediate•
lesson•
November 30, 2026•
~5 min read

The property gives ten percent off any stay of seven nights or more. Ask where that rule lives and the answer is app/Traits/CalculatesPrice.php, a file named after a PHP language feature.

PHP
<?php declare(strict_types=1); namespace App\Traits; use App\Models\Room; use Carbon\CarbonImmutable; trait CalculatesPrice { public function totalCentsFor(Room $room, CarbonImmutable $checkIn, CarbonImmutable $checkOut): int { $nights = (int) $checkIn->diffInDays($checkOut); $total = $nights * $room->roomType->nightly_rate_cents; if ($nights >= 7) { $total = (int) round($total * 0.9); } return $total; } public function calculateTotalCents(): int { return $this->totalCentsFor($this->room, $this->check_in, $this->check_out); } }

The trait exists because two classes needed the formula. The quote page prices a stay before any reservation exists, and the Reservation model prices itself. So the formula went into a trait and both classes pull it in.

PHP
<?php declare(strict_types=1); namespace App\Services; use App\Traits\CalculatesPrice; final class QuoteService { use CalculatesPrice; }
PHP
<?php declare(strict_types=1); namespace App\Models; use App\Traits\CalculatesPrice; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; class Reservation extends Model { use CalculatesPrice; protected $fillable = [ 'guest_id', 'room_id', 'check_in', 'check_out', 'adults', 'children', 'status', 'total_cents', 'confirmation_code', 'confirmed_at', ]; protected function casts(): array { return [ 'check_in' => 'immutable_date', 'check_out' => 'immutable_date', 'confirmed_at' => 'immutable_datetime', ]; } public function guest(): BelongsTo { return $this->belongsTo(Guest::class); } public function room(): BelongsTo { return $this->belongsTo(Room::class); } public function payments(): HasMany { return $this->hasMany(Payment::class); } public function outstandingCents(): int { return $this->total_cents - (int) $this->paid_cents; } }

QuoteService is an empty class whose only content is a use statement. It exists so that something in app/Services can be injected. That is a sign the trait is doing a class's job.

What a trait is

A trait is copy-paste that PHP performs at compile time. The method body is flattened into every class that uses it, so after loading there are two totalCentsFor() methods in memory, one on QuoteService and one on Reservation, with identical bodies and different $this. The trait looks like organisation, because the model file got shorter. The rule did not move anywhere. It got stapled onto two classes, and a business rule shared that way has three costs.

You cannot vary the rule per context. The moment a rate plan (a named price with its own conditions, such as a non-refundable rate) appears that excludes the weekly discount, the trait has one body to express the difference in. It grows an if on something it reaches for through $this, and now the rule branches on which class happens to host it.

You cannot substitute it in a test. The formula is fused to the model, so a test of anything that prices a reservation runs the real formula, every time, with a real Room and a loaded roomType relation. There is no pricing collaborator to hand a fake to.

The dependencies are hidden. The trait reads $room->roomType->nightly_rate_cents, which means it needs the roomType relation loadable at call time. The trait's calculateTotalCents() reaches for $this->room, $this->check_in and $this->check_out, which QuoteService does not have, so it only works on a model. Nothing in either class's constructor says any of this.

A class named after the rule

The rule is about pricing a stay from a nightly rate, so the class is NightlyRatePricing, in a folder named after what it does. It takes the room type, because the rate lives there, and the dates.

PHP
<?php declare(strict_types=1); namespace App\Pricing; use App\Models\RoomType; use Carbon\CarbonImmutable; final readonly class NightlyRatePricing { private const WEEKLY_DISCOUNT_PERCENT = 10; private const WEEKLY_DISCOUNT_MINIMUM_NIGHTS = 7; public function totalCents(RoomType $roomType, CarbonImmutable $checkIn, CarbonImmutable $checkOut): int { $nights = (int) $checkIn->diffInDays($checkOut); $total = $nights * $roomType->nightly_rate_cents; if ($nights >= self::WEEKLY_DISCOUNT_MINIMUM_NIGHTS) { $total = (int) round($total * (100 - self::WEEKLY_DISCOUNT_PERCENT) / 100); } return $total; } }

The seven-night rule now has exactly one home. QuoteService and the trait are deleted. The model loses use CalculatesPrice;, and calculateTotalCents() goes with the trait. It keeps the fields and relations that are about its own row.

RequestReservation asks for the pricing class in its constructor, the way the previous lesson taught, and passes it the loaded room type.

PHP
<?php declare(strict_types=1); namespace App\Services; use App\Mail\ReservationConfirmation; use App\Models\Guest; use App\Models\Reservation; use App\Models\Room; use App\Pricing\NightlyRatePricing; use Carbon\CarbonImmutable; use Illuminate\Contracts\Mail\Mailer; use Illuminate\Support\Str; final readonly class RequestReservation { public function __construct( private NightlyRatePricing $pricing, private Mailer $mailer, ) { } /** * @param array<string, mixed> $attributes */ public function handle(int $guestId, array $attributes): Reservation { $guest = Guest::query()->findOrFail($guestId); $room = Room::query()->with('roomType')->findOrFail($attributes['room_id']); $checkIn = CarbonImmutable::parse($attributes['check_in']); $checkOut = CarbonImmutable::parse($attributes['check_out']); $reservation = Reservation::query()->create([ 'guest_id' => $guest->id, 'room_id' => $room->id, 'check_in' => $checkIn, 'check_out' => $checkOut, 'adults' => $attributes['adults'], 'children' => $attributes['children'], 'status' => 'confirmed', 'confirmed_at' => CarbonImmutable::now(), 'confirmation_code' => Str::upper(Str::random(8)), 'total_cents' => $this->pricing->totalCents($room->roomType, $checkIn, $checkOut), ]); $this->mailer->to($guest->email)->send(new ReservationConfirmation($reservation)); return $reservation; } }

The quote page injects NightlyRatePricing the same way, and the RequestReservationTest passes new NightlyRatePricing() where it passed new QuoteService().

The rule gets its own test

Because the class takes a room type and two dates and returns an integer, the rule can be tested with no database and no booted application. An Eloquent model can be instantiated and have attributes set without a connection, as long as nothing on it is saved or queried.

PHP
<?php declare(strict_types=1); namespace Tests\Unit\Pricing; use App\Models\RoomType; use App\Pricing\NightlyRatePricing; use Carbon\CarbonImmutable; use PHPUnit\Framework\TestCase; final class NightlyRatePricingTest extends TestCase { public function test_a_six_night_stay_pays_the_full_rate(): void { $roomType = new RoomType(); $roomType->nightly_rate_cents = 12000; $total = (new NightlyRatePricing())->totalCents( $roomType, CarbonImmutable::parse('2026-10-01'), CarbonImmutable::parse('2026-10-07'), ); $this->assertSame(72000, $total); } public function test_a_seven_night_stay_gets_ten_percent_off(): void { $roomType = new RoomType(); $roomType->nightly_rate_cents = 12000; $total = (new NightlyRatePricing())->totalCents( $roomType, CarbonImmutable::parse('2026-10-01'), CarbonImmutable::parse('2026-10-08'), ); $this->assertSame(75600, $total); } }

With the trait, these tests needed a reservation with a room with a room type, and they ran through $this->room->roomType. Now they need one object and two dates.

Rate plans will eventually want a say in this formula. When that day comes there is one class to change, or one interface to put in front of it, and RequestReservation will not change.

The one thing to remember

A trait shares code, not a concept. A business rule that two classes need gets a class named after the rule, injected into both, so it can be varied, substituted, and tested on its own.

Course Content