Never Run a Query Inside an Accessor
An accessor looks like a property, so nobody opens the model to see what it does. Show $reservation->outstanding_balance in a Blade loop over forty arrivals and the page runs forty extra select sum(...) queries, one per row. The controller's with() calls look careful and change nothing, and no single query is slow enough to reach the slow query log.
Don't do this
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Reservation extends Model
{
public function payments(): HasMany
{
return $this->hasMany(Payment::class);
}
protected function outstandingBalance(): Attribute
{
return Attribute::make(
get: fn (): int => $this->total_cents - (int) $this->payments()->sum('amount_cents'),
);
}
}Do this instead
The model keeps a method that does arithmetic on what is already loaded.
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Reservation extends Model
{
public function payments(): HasMany
{
return $this->hasMany(Payment::class);
}
public function outstandingCents(): int
{
return $this->total_cents - (int) $this->paid_cents;
}
}The query loads the paid total as a column, in the same statement as the reservations.
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Models\Reservation;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Collection;
final readonly class TodaysArrivals
{
/**
* @return Collection<int, Reservation>
*/
public function get(): Collection
{
return Reservation::query()
->whereDate('check_in', CarbonImmutable::today())
->withSum('payments as paid_cents', 'amount_cents')
->get();
}
}withSum() adds the total as a subselect column, so forty arrivals cost one query. Without the as paid_cents alias the column is named payments_sum_amount_cents. It is null for a reservation with no payments, which is why the method casts to int.
Strict mode did not catch the accessor because its lazy loading guard only fires when code reads a relation as a property ($reservation->payments). Calling $this->payments() skips that path. It does help the method: with Model::shouldBeStrict() on, outstandingCents() on a reservation loaded without withSum() throws a MissingAttributeException naming paid_cents, instead of reporting the full total as owed.