Refactoring Ergodnc - Query Handlers for Laravel List Endpoints
Ergodnc is the office-rental API Mohamed Said built live on the official Laravel YouTube channel (themsaid/ergodnc, read at commit 42907c0). This piece covers its three listing endpoints: GET /offices, GET /reservations for the Guest, and GET /host/reservations for the Host. It shows the original, what is wrong with it, and a rebuild as three read slices with query handlers.
Ergodnc runs Laravel 8. The rebuild targets Laravel 13.
What the endpoints do today
The host listing is HostReservationController::index() at app/Http/Controllers/HostReservationController.php:13-44. It is registered at routes/api.php:44 as Route::get('/host/reservations', [HostReservationController::class, 'index']); with no middleware:
<?php
namespace App\Http\Controllers;
use App\Http\Resources\ReservationResource;
use App\Models\Reservation;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Validation\Rule;
class HostReservationController extends Controller
{
public function index()
{
abort_unless(auth()->user()->tokenCan('reservations.show'),
Response::HTTP_FORBIDDEN
);
validator(request()->all(), [
'status' => [Rule::in([Reservation::STATUS_ACTIVE, Reservation::STATUS_CANCELLED])],
'office_id' => ['integer'],
'user_id' => ['integer'],
'from_date' => ['date', 'required_with:to_date'],
'to_date' => ['date', 'required_with:from_date', 'after:from_date'],
])->validate();
$reservations = Reservation::query()
->whereRelation('office', 'user_id', '=', auth()->id())
->when(request('office_id'),
fn($query) => $query->where('office_id', request('office_id'))
)->when(request('user_id'),
fn($query) => $query->where('user_id', request('user_id'))
)->when(request('status'),
fn($query) => $query->where('status', request('status'))
)->when(request('from_date') && request('to_date'),
fn($query) => $query->betweenDates(request('from_date'), request('to_date'))
)
->with(['office.featuredImage'])
->paginate(20);
return ReservationResource::collection(
$reservations
);
}
}The guest listing at app/Http/Controllers/UserReservationController.php:22-50 is the same method with ->where('user_id', auth()->id()) at line 36 instead of the whereRelation, and without the user_id filter. Its route at routes/api.php:39 carries auth:sanctum and verified.
The office listing is OfficeController::index() at app/Http/Controllers/OfficeController.php:22-53, served by the public route at routes/api.php:28. Anyone may browse offices, so the missing middleware there is correct:
<?php
namespace App\Http\Controllers;
use App\Http\Resources\OfficeResource;
use App\Models\Office;
use App\Models\Reservation;
use Illuminate\Http\Resources\Json\JsonResource;
class OfficeController extends Controller
{
// show(), create(), update(), and delete() omitted
public function index(): JsonResource
{
$offices = Office::query()
->when(request('user_id') && auth()->user() && request('user_id') == auth()->id(),
fn($builder) => $builder,
fn($builder) => $builder->where('approval_status', Office::APPROVAL_APPROVED)->where('hidden', false)
)
->when(request('user_id'), fn($builder) => $builder->whereUserId(request('user_id')))
->when(request('visitor_id'),
fn($builder) => $builder->whereRelation('reservations', 'user_id', '=', request('visitor_id'))
)
->when(
request('lat') && request('lng'),
fn($builder) => $builder->nearestTo(request('lat'), request('lng')),
fn($builder) => $builder->orderBy('id', 'ASC')
)
->when(request('tags'),
fn($builder) => $builder->whereHas(
'tags',
fn ($builder) => $builder->whereIn('id', request('tags')),
'=',
count(request('tags'))
)
)
->with(['images', 'tags', 'user'])
->withCount(['reservations' => fn($builder) => $builder->whereStatus(Reservation::STATUS_ACTIVE)])
->paginate(20);
return OfficeResource::collection(
$offices
);
}
}What is wrong with it
/host/reservationshas no auth middleware (routes/api.php:44), while the controller callsauth()->user()->tokenCan(...)on its first line (HostReservationController.php:15). An anonymous request reaches that line withauth()->user()returning null, so it ends in a PHP error and a 500 instead of a 401. I read this from the source and did not run it. A host's reservations are owned data, and the guest listing's route already has the middleware.Nothing is a slice. Each listing is one controller method that builds the query and picks the resource, the reservation listings also check the ability and validate their filters inline, and the pieces sit in Laravel's type folders (
app/Http/Controllers,app/Models,app/Http/Resources).All three methods read filters from
request()inside the query builder: thirteen calls in the office listing (OfficeController.php:25-43), ten in the host query builder (HostReservationController.php:27-39), eight in the guest one (UserReservationController.php:35-43). A method written like that cannot run from a console command or a unit test without faking an HTTP request.The office listing has no validation.
count(request('tags'))atOfficeController.php:43receives the string"1"for?tags=1, andcount()throws aTypeErroron PHP 8 (read from the source, not run). The reservation listings validate inline through thevalidator()helper (HostReservationController.php:19-25,UserReservationController.php:28-33) instead of a Form Request.request('lat') && request('lng')(OfficeController.php:34) is false for the string"0", so a search at latitude 0 silently falls back to ordering by id.Visibility is decided from request input.
OfficeController.php:25-28comparesrequest('user_id')withauth()->id()and lets that comparison pick between "everything" and "approved and visible only". The result is right, but the decision is built from the request instead of from the authenticated user, on a route that has no auth middleware and needs anauth()->user()null check to survive.The ability is the string
'reservations.show', checked inline withabort_unless(HostReservationController.php:15,UserReservationController.php:24).Status filters use the int constants
Reservation::STATUS_ACTIVEandSTATUS_CANCELLED(HostReservationController.php:20,UserReservationController.php:29,OfficeController.php:47), and the visibility rule usesOffice::APPROVAL_APPROVED(OfficeController.php:27).Offices and reservations are fused through relations. The office listing filters through
whereRelation('reservations', ...)(line 31), counts withwithCount('reservations')(line 47), and loadsuser(line 46). The host listing finds its reservations throughwhereRelation('office', 'user_id', ...)(HostReservationController.php:28) and loadsoffice.featuredImage(line 38), and the guest listing loads the same office (UserReservationController.php:44).The resources spread every column of the model with
Arr::except(parent::toArray($request), [...])(OfficeResource.php:25,ReservationResource.php:21, whose exclusion list is empty). Adding a column adds a field to the API, and both reservation listings already returnwifi_passwordto whoever calls them.The page size
20is a bare number in all three methods (OfficeController.php:48,HostReservationController.php:39,UserReservationController.php:45).The controllers are multi-action.
UserReservationControllerholdsindex,create, andcancel, andOfficeControllerholdsindex,show,create,update, anddelete, where each action belongs in its own slice.The distance formula in
scopeNearestTocarries two bare numbers,69.1and57.3(Office.php:60), with nothing saying they are miles per degree of latitude and degrees per radian.auth(),request(), andvalidator()resolve their dependencies from the container globally, so the classes hide what they need.None of the three routes has a name (
routes/api.php:28,:39,:44).
The refactor
The rebuild splits the app into the modules App\Offices, App\Reservations, and App\Identity. Neither of the first two imports the other: where a listing needs the other module's data, it comes through a contract or is dropped.
Before, at commit 42907c0:
app/
Http/
Controllers/
HostReservationController.php
OfficeController.php
UserReservationController.php
Kernel.php
Resources/
ImageResource.php
OfficeResource.php
ReservationResource.php
TagResource.php
UserResource.php
Models/
Image.php
Office.php
Reservation.php
Tag.php
User.php
Providers/
AppServiceProvider.php
database/migrations/
2021_09_09_124245_create_offices_table.php
2021_09_09_124300_create_reservations_table.php
routes/api.phpAfter the rebuild:
app/
Identity/
IdentityServiceProvider.php
User/User.php
Offices/
Contracts/
ActiveReservations.php
OfficeReservations.php
Image/Image.php
ListOffices/
ListOfficesController.php
ListOfficesQuery.php
ListOfficesQueryHandler.php
ListOfficesRequest.php
ListOfficesResource.php
ListOfficesResult.php
OfficeImage.php
OfficeImageResource.php
OfficeListItem.php
OfficeTagResource.php
Office/
Office.php
OfficeApprovalStatus.php
OfficeFactory.php
Tag/Tag.php
OfficesServiceProvider.php
offices-routes.php
Reservations/
Integrations/ReservationsForOffices.php
ListGuestReservations/
ListGuestReservationsController.php
ListGuestReservationsQuery.php
ListGuestReservationsQueryHandler.php
ListGuestReservationsRequest.php
ListGuestReservationsResource.php
ListGuestReservationsResult.php
ListHostReservations/
ListHostReservationsController.php
ListHostReservationsQuery.php
ListHostReservationsQueryHandler.php
ListHostReservationsRequest.php
ListHostReservationsResource.php
ListHostReservationsResult.php
BackfillReservationHosts/
BackfillReservationHosts.php
Reservation/
Reservation.php
ReservationStatus.php
ReservationAbility.php
ReservationsServiceProvider.php
reservations-routes.php
bootstrap/
app.php
providers.php
database/migrations/
2026_10_12_000001_add_host_user_id_to_reservations_table.php
2026_10_12_000002_make_host_user_id_required_on_reservations_table.php
2026_10_12_000003_convert_reservation_status_to_string.php
2026_10_12_000004_convert_office_approval_status_to_string.phpI show the office listing in full because it has the most to say: a visibility rule, filters, and a number that belongs to the other module. The two reservation slices have the same shape, so I only show what is different about them. Each folder holds the query, handler, result, Form Request, controller, and resource for its listing. The office listing also has a list item, for the data that does not come from the Office model.
The visibility rule on the model
The when() at OfficeController.php:25-28 becomes a named query method on the Offices Office model. Callers pass the viewer they resolved from the authenticated user, and the model decides what that viewer may see. The reservations() and user() relations are gone, approval_status is cast to an OfficeApprovalStatus string enum ('pending', 'approved', replacing Office::APPROVAL_PENDING and APPROVAL_APPROVED at Office.php:18-19, with a migration that changes the approval_status column from tinyInteger to a string with a default of 'pending' and converts the stored 1 and 2), and nearestTo() keeps the distance formula from Office.php:55-63 minus its no-op ->select(), with the bare 69.1 and 57.3 named as private constants. Image and Tag are the Offices models behind images() and tags(). OfficeFactory sits in the same App\Offices\Office\ folder as the model.
<?php
declare(strict_types=1);
namespace App\Offices\Office;
use App\Offices\Image\Image;
use App\Offices\Tag\Tag;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* @use HasFactory<OfficeFactory>
*/
final class Office extends Model
{
use HasFactory;
use SoftDeletes;
private const float MILES_PER_DEGREE_OF_LATITUDE = 69.1;
private const float DEGREES_PER_RADIAN = 57.3;
/**
* Offices the viewer may browse, optionally only one host's. A host browsing
* their own offices sees every state; everyone else sees approved, visible
* offices only.
*
* @return Builder<Office>
*/
public static function listedFor(?int $viewerId, ?int $hostUserId): Builder
{
$query = self::query()
->when($hostUserId !== null, fn (Builder $builder) => $builder->where('user_id', $hostUserId));
if ($hostUserId !== null && $hostUserId === $viewerId) {
return $query;
}
return $query
->where('approval_status', OfficeApprovalStatus::APPROVED)
->where('hidden', false);
}
// Methods used by other slices, such as submit() and revise(), are omitted.
public function images(): MorphMany
{
return $this->morphMany(Image::class, 'resource');
}
public function tags(): BelongsToMany
{
return $this->belongsToMany(Tag::class, 'offices_tags');
}
/**
* @param Builder<Office> $builder
* @return Builder<Office>
*/
public function scopeNearestTo(Builder $builder, float $lat, float $lng): Builder
{
$miles = self::MILES_PER_DEGREE_OF_LATITUDE;
$degrees = self::DEGREES_PER_RADIAN;
return $builder->orderByRaw(
"POW({$miles} * (lat - ?), 2) + POW({$miles} * (? - lng) * COS(lat / {$degrees}), 2)",
[$lat, $lng]
);
}
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'user_id' => 'integer',
'featured_image_id' => 'integer',
'lat' => 'decimal:8',
'lng' => 'decimal:8',
'approval_status' => OfficeApprovalStatus::class,
'hidden' => 'boolean',
'price_per_day' => 'integer',
'monthly_discount' => 'integer',
];
}
}The rule that used to sit in a closure inside the controller now has a name and a typed signature, and the query handler cannot get it wrong by reading a different request key.
Reservation data for the office listing
The listing needs two facts that live in Reservations: how many active reservations each office has, and which offices a visitor has reserved (the visitor_id filter). Offices defines what it needs, Reservations implements it:
<?php
declare(strict_types=1);
namespace App\Offices\Contracts;
interface OfficeReservations
{
/**
* @param list<int> $officeIds
* @return array<int, int> active reservation count keyed by office id; offices with none are absent
*/
public function activeCountsFor(array $officeIds): array;
/**
* Offices the guest has a reservation on, in any status.
*
* @return list<int>
*/
public function officeIdsReservedBy(int $guestUserId): array;
}I read these at request time through the contract and did not materialise the count. A materialised count would need Offices to subscribe to Reservations' events, and a listener cannot name those event classes without importing them. A read-only ConnectionInterface query would also work, but it hard-codes the reservations table and its status values into Offices. The implementation, bound in ReservationsServiceProvider, answers a whole page with one grouped query:
<?php
declare(strict_types=1);
namespace App\Reservations\Integrations;
use App\Offices\Contracts\ActiveReservations;
use App\Offices\Contracts\OfficeReservations;
use App\Reservations\Reservation\Reservation;
use App\Reservations\Reservation\ReservationStatus;
final readonly class ReservationsForOffices implements ActiveReservations, OfficeReservations
{
// existFor(), from ActiveReservations (the office delete check), is omitted.
public function activeCountsFor(array $officeIds): array
{
return Reservation::query()
->where('status', ReservationStatus::ACTIVE)
->whereIn('office_id', $officeIds)
->groupBy('office_id')
->selectRaw('office_id, count(*) as active_count')
->pluck('active_count', 'office_id')
->map(fn (mixed $count): int => (int) $count)
->all();
}
public function officeIdsReservedBy(int $guestUserId): array
{
return Reservation::query()
->where('user_id', $guestUserId)
->distinct()
->pluck('office_id')
->values()
->all();
}
}The office listing slice
<?php
declare(strict_types=1);
namespace App\Offices\ListOffices;
final readonly class ListOfficesQuery
{
/**
* @param list<int> $tagIds
*/
public function __construct(
public ?int $viewerId,
public ?int $hostUserId,
public ?int $visitorId,
public ?float $latitude,
public ?float $longitude,
public array $tagIds,
public int $page,
) {
}
}viewerId is the only place the principal appears, and nothing downstream reads the request again.
<?php
declare(strict_types=1);
namespace App\Offices\ListOffices;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
final class ListOfficesRequest extends FormRequest
{
private const FIRST_PAGE = 1;
public function authorize(): bool
{
return true;
}
/**
* @return array<string, list<mixed>>
*/
public function rules(): array
{
return [
'user_id' => ['nullable', 'integer'],
'visitor_id' => ['nullable', 'integer'],
'lat' => ['nullable', 'required_with:lng', 'numeric'],
'lng' => ['nullable', 'required_with:lat', 'numeric'],
'tags' => ['nullable', 'array'],
'tags.*' => ['integer', Rule::exists('tags', 'id')],
'page' => ['nullable', 'integer', 'min:1'],
];
}
public function hostUserId(): ?int
{
return $this->filled('user_id') ? $this->integer('user_id') : null;
}
public function visitorId(): ?int
{
return $this->filled('visitor_id') ? $this->integer('visitor_id') : null;
}
public function latitude(): ?float
{
return $this->filled('lat') ? $this->float('lat') : null;
}
public function longitude(): ?float
{
return $this->filled('lng') ? $this->float('lng') : null;
}
/**
* @return list<int>
*/
public function tagIds(): array
{
return $this->filled('tags') ? array_map(intval(...), $this->array('tags')) : [];
}
public function page(): int
{
return $this->filled('page') ? $this->integer('page') : self::FIRST_PAGE;
}
}Empty values for the optional filters are ignored, as before. authorize() returns true because the route is public. The user_id parameter keeps its name on the wire and becomes hostUserId in code, because it means "offices hosted by this user". The tags array is validated before anything counts it, which is the TypeError fix, and lat=0 now counts as a latitude.
<?php
declare(strict_types=1);
namespace App\Offices\ListOffices;
use App\Offices\Contracts\OfficeReservations;
use App\Offices\Office\Office;
use Illuminate\Contracts\Filesystem\Cloud;
use Illuminate\Database\Eloquent\Builder;
final readonly class ListOfficesQueryHandler
{
public const PER_PAGE = 20;
public function __construct(
private OfficeReservations $reservations,
private Cloud $disk,
) {
}
public function handle(ListOfficesQuery $query): ListOfficesResult
{
$page = Office::listedFor($query->viewerId, $query->hostUserId)
->when($query->visitorId !== null, fn (Builder $builder) => $builder->whereIn(
'id',
$this->reservations->officeIdsReservedBy($query->visitorId),
))
->when(
$query->latitude !== null && $query->longitude !== null,
fn (Builder $builder) => $builder->nearestTo($query->latitude, $query->longitude),
fn (Builder $builder) => $builder->orderBy('id'),
)
->when($query->tagIds !== [], fn (Builder $builder) => $builder->whereHas(
'tags',
fn (Builder $tags) => $tags->whereIn('id', $query->tagIds),
'=',
count($query->tagIds),
))
->with(['images', 'tags'])
->paginate(perPage: self::PER_PAGE, page: $query->page);
$activeCounts = $this->reservations->activeCountsFor($page->pluck('id')->all());
return new ListOfficesResult($page->through(
fn (Office $office): OfficeListItem => OfficeListItem::fromOffice(
$office,
$activeCounts[$office->id] ?? 0,
$this->disk,
),
));
}
}ListOfficesResult has one property, offices: a LengthAwarePaginator of OfficeListItem, with through() swapping each Office for an OfficeListItem in place. paginate() already took the page's path from the current request, so the resource collection still produces Laravel's links and meta.
OfficeListItem is a readonly object holding the Office, its activeReservationsCount, and its images as a list of readonly OfficeImage objects (id, path, resourceType, resourceId, createdAt, updatedAt), built by fromOffice(Office, int $activeReservationsCount, Cloud $disk). The images are the one part the resource cannot read from the model: path is the disk's url() for the stored file, the same URL Storage::url() built in ImageResource.php:19 (the original reads the default disk too), and a resource has no constructor to inject the disk into. So the handler takes the disk as a Cloud (the contract that declares url()) and passes it in. Everything else comes straight from the models: OfficeTagResource reads id and name from Tag, OfficeImageResource names its keys and serialises both dates through toIso8601String(), and ListOfficesResource names every key it reads from Office, so a new column on offices no longer reaches the API:
<?php
declare(strict_types=1);
namespace App\Offices\ListOffices;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @property OfficeListItem $resource
*/
final class ListOfficesResource extends JsonResource
{
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
$office = $this->resource->office;
return [
'id' => $office->id,
'host_user_id' => $office->user_id,
'title' => $office->title,
'description' => $office->description,
'lat' => $office->lat,
'lng' => $office->lng,
'address_line1' => $office->address_line1,
'address_line2' => $office->address_line2,
'approval_status' => $office->approval_status->value,
'hidden' => $office->hidden,
'price_per_day' => $office->price_per_day,
'monthly_discount' => $office->monthly_discount,
'featured_image_id' => $office->featured_image_id,
'reservations_count' => $this->resource->activeReservationsCount,
'images' => OfficeImageResource::collection($this->resource->images),
'tags' => $this->when(
$office->relationLoaded('tags'),
fn () => OfficeTagResource::collection($office->tags),
),
];
}
}<?php
declare(strict_types=1);
namespace App\Offices\ListOffices;
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Http\JsonResponse;
use Knuckles\Scribe\Attributes\Endpoint;
use Knuckles\Scribe\Attributes\Group;
use Knuckles\Scribe\Attributes\QueryParam;
use Knuckles\Scribe\Attributes\Response;
use Knuckles\Scribe\Attributes\Unauthenticated;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
#[Group('Offices')]
final readonly class ListOfficesController
{
public function __construct(
private Dispatcher $bus,
) {
}
#[Endpoint('List offices', 'Lists approved, visible offices. A host who passes their own user_id also sees their hidden and pending offices.')]
#[Unauthenticated]
#[QueryParam('user_id', 'integer', 'Only offices hosted by this user.', required: false, example: 3)]
#[QueryParam('visitor_id', 'integer', 'Only offices this user has reserved.', required: false, example: 5)]
#[QueryParam('lat', 'number', 'Latitude to sort by distance. Required with lng.', required: false, example: 40.7128)]
#[QueryParam('lng', 'number', 'Longitude to sort by distance. Required with lat.', required: false, example: -74.006)]
#[QueryParam('tags', 'integer[]', 'Only offices that have all of these tag ids.', required: false, example: [1, 2])]
#[QueryParam('page', 'integer', 'Page number, 20 offices per page.', required: false, example: 1)]
#[Response(
content: [
'data' => [
[
'id' => 7,
'host_user_id' => 3,
'title' => 'Corner office on Broadway',
'description' => 'Quiet room with a view.',
'lat' => '40.71280000',
'lng' => '-74.00600000',
'address_line1' => '1 Broadway',
'address_line2' => null,
'approval_status' => 'approved',
'hidden' => false,
'price_per_day' => 1000,
'monthly_discount' => 10,
'featured_image_id' => 12,
'reservations_count' => 2,
'images' => [
[
'id' => 12,
'path' => 'https://ergodnc.test/storage/office_image.jpg',
'resource_type' => 'office',
'resource_id' => 7,
'created_at' => '2026-10-01T08:00:00+00:00',
'updated_at' => '2026-10-01T08:00:00+00:00',
],
],
'tags' => [
['id' => 1, 'name' => 'has_ac'],
],
],
],
'links' => [
'first' => 'https://ergodnc.test/offices?page=1',
'last' => 'https://ergodnc.test/offices?page=1',
'prev' => null,
'next' => null,
],
'meta' => [
'current_page' => 1,
'from' => 1,
'last_page' => 1,
'links' => [
['url' => null, 'label' => '« Previous', 'page' => null, 'active' => false],
['url' => 'https://ergodnc.test/offices?page=1', 'label' => '1', 'page' => 1, 'active' => true],
['url' => null, 'label' => 'Next »', 'page' => null, 'active' => false],
],
'path' => 'https://ergodnc.test/offices',
'per_page' => 20,
'to' => 1,
'total' => 1,
],
],
status: SymfonyResponse::HTTP_OK,
)]
public function __invoke(ListOfficesRequest $request): JsonResponse
{
$result = $this->bus->dispatch(new ListOfficesQuery(
viewerId: $request->user()?->id,
hostUserId: $request->hostUserId(),
visitorId: $request->visitorId(),
latitude: $request->latitude(),
longitude: $request->longitude(),
tagIds: $request->tagIds(),
page: $request->page(),
));
return ListOfficesResource::collection($result->offices)
->response()
->setStatusCode(SymfonyResponse::HTTP_OK);
}
}$request->user()?->id is the one place the principal is read. On a route with no auth middleware it still resolves a bearer token, because config/auth.php:17 sets the default guard to sanctum, and it returns null for an anonymous browse, which sends listedFor() down the restricted branch. The route stays public, is named offices.offices.list, and lives in offices-routes.php.
The reservation listings
ListHostReservations follows the same shape, and three things differ. The Host's id comes from $request->user()->id and is the only principal input. The handler filters on host_user_id, the column the reservation copies from the office at booking, so it never asks Offices who the host is. And the response no longer embeds the office: office_id stays, and a client that wants the title or image calls the offices endpoint. That drops a cross-module read and, with it, the need for an Offices contract here.
<?php
declare(strict_types=1);
namespace App\Reservations\ListHostReservations;
use App\Reservations\Reservation\Reservation;
use Illuminate\Database\Eloquent\Builder;
final readonly class ListHostReservationsQueryHandler
{
public const PER_PAGE = 20;
public function handle(ListHostReservationsQuery $query): ListHostReservationsResult
{
$page = Reservation::query()
->where('host_user_id', $query->hostUserId)
->when($query->officeId !== null, fn (Builder $builder) => $builder->where('office_id', $query->officeId))
->when($query->guestUserId !== null, fn (Builder $builder) => $builder->where('user_id', $query->guestUserId))
->when($query->status !== null, fn (Builder $builder) => $builder->where('status', $query->status))
->when(
$query->fromDate !== null && $query->toDate !== null,
fn (Builder $builder) => $builder->betweenDates($query->fromDate, $query->toDate),
)
->orderBy('id')
->paginate(perPage: self::PER_PAGE, page: $query->page);
return new ListHostReservationsResult($page);
}
}Three Reservations facts these slices rely on: host_user_id is a new column on reservations, copied from the office at booking because an office never changes host, added nullable, backfilled by a one-off command that reads offices by id through an injected ConnectionInterface, then made required (two migrations around a BackfillReservationHosts console command); ReservationStatus is a string enum (active, cancelled, with label()) and a migration changes the column to a string with a default of 'active' and converts the stored 1 and 2; and Reservation has no office() or user() relation.
ListHostReservationsQuery carries hostUserId, status (?ReservationStatus), officeId, guestUserId, fromDate, toDate, and page. ListHostReservationsRequest validates status with Rule::enum(ReservationStatus::class), office_id and user_id as integers, the from_date/to_date pair as in the original, and page, and returns status() as the enum. Its authorize() returns true, because the route middleware already authenticates and the ability check lives there. There is no list item, because everything the response shows is on the Reservation model: ListHostReservationsResult holds the paginator of models as reservations, and ListHostReservationsResource reads the model. It names eight keys (id, user_id, office_id, status, price, start_date, end_date, created_at), serialises the dates through toIso8601String(), and leaves wifi_password out, because a host has no use for the password the original handed them.
The controller has the same shape as the office one: it dispatches the query, wraps the result's paginator in the resource collection, and returns it with SymfonyResponse::HTTP_OK. It carries #[Group('Reservations')], #[Authenticated], a #[QueryParam] for each of status (with enum: ReservationStatus::class), office_id, user_id, from_date, to_date, and page, and a #[Response] whose item has the eight resource keys. The resource emits the guest as user_id, the key the original used.
ListGuestReservations is the host slice with the guest as the principal. Its query carries guestUserId taken from $request->user()->id, its request has no user_id rule, its handler filters on user_id instead of host_user_id, and its resource keeps wifi_password, since the guest is the person it was generated for. Each slice has its own request, result, and resource rather than importing the other's. The two requests overlap on four rules, but a shared class would sit outside both slices and grow a conditional the day one listing gains a filter the other does not want.
Routes and wiring
Both reservation listings go into one group, and the group is where the missing middleware comes back. The ability strings become the ReservationAbility::SHOW constant ('reservations.show', unchanged because existing tokens carry it) and abilities: middleware replaces the abort_unless(...) line at the top of each old method:
<?php
declare(strict_types=1);
use App\Reservations\ListGuestReservations\ListGuestReservationsController;
use App\Reservations\ListHostReservations\ListHostReservationsController;
use App\Reservations\ReservationAbility;
use Illuminate\Support\Facades\Route;
// Routes from the other slices in this module are omitted.
Route::middleware(['auth:sanctum', 'verified', 'abilities:'.ReservationAbility::SHOW])->group(function (): void {
Route::get('/reservations', ListGuestReservationsController::class)
->name('reservations.reservations.list');
Route::get('/host/reservations', ListHostReservationsController::class)
->name('reservations.host-reservations.list');
});The abilities alias points at Sanctum's CheckAbilities and is registered in bootstrap/app.php, and bootstrap/providers.php lists the three module providers, which also calls $middleware->throttleApi() because ergodnc throttles every API route (app/Http/Kernel.php:44) and Laravel 13 only adds that to the api group when asked. ReservationsServiceProvider maps each query to its handler with Bus::map(), loads the route file inside the api middleware group, and binds OfficeReservations and ActiveReservations to ReservationsForOffices, the one class that answers every question Offices asks Reservations. OfficesServiceProvider maps ListOfficesQuery to its handler and registers the office morph alias with Relation::enforceMorphMap(['office' => Office::class]), so the resource_type stored on images (already office in ergodnc, AppServiceProvider.php:33-36) resolves to App\Offices\Office\Office. It also hands ListOfficesQueryHandler the default disk with a contextual binding, when(ListOfficesQueryHandler::class)->needs(Cloud::class), that returns Factory::disk(). Without it, the container would inject the filesystems.cloud disk, which falls back to S3, while the original built image URLs from the default disk. IdentityServiceProvider, in the module that owns the User model, registers 'user' the same way, because the original map covers both models and Sanctum's tokens() relation fails on an unmapped user once any map is enforced. enforceMorphMap() merges into the existing map by default.
What changed in the API contract
GET /host/reservationsreturns 401 for an anonymous request. Before, read from the source, it returned a 500. It also now requires a verified email (403 otherwise), as the guest listing already did.A token without the
reservations.showability gets 403 with the message "Invalid ability provided." from Sanctum's middleware, on both reservation listings.GET /officesreturns 422 for a non-arraytags, an unknown tag id, a non-numericlatorlng, alatwithoutlng, a non-integeruser_idorvisitor_id, and apagethat is not a positive integer. Both reservation listings also return 422 for apagethat is not a positive integer, which the originals did not validate. Before,?tags=1threw aTypeError.lat=0orlng=0now sorts by distance. Before, a zero fell back to ordering by id.The
statusfilter on the reservation listings takesactiveorcancelledinstead of1or2, and returns 422 for anything else.statusin the response is the same string.approval_statusin the office listing is"pending"or"approved"instead of1or2.Each office in
GET /officesreplaces the nesteduserobject withhost_user_id, keepsimagesas they were apart from the date format, and lists tags as{"id", "name"}without thepivotobject. The keyreservations_countstays and still counts active reservations only.Both reservation listings drop the nested
officeobject and keepoffice_id. They also dropupdated_at.wifi_passwordis gone fromGET /host/reservations.GET /reservationsstill returns it.start_date,end_date, andcreated_aton reservations, andcreated_atandupdated_aton office images, change format from2026-11-02T00:00:00.000000Zto2026-11-02T00:00:00+00:00.GET /host/reservationsnow also lists reservations of soft-deleted offices. The original filtered throughwhereRelation('office', ...), which hides them; the rebuild filters on the reservation's ownhost_user_id.Reservation listings are ordered by id. Before, they had no
ORDER BY, so the page order was whatever the database returned.
A first pass
This is a first pass, and there is more I would change. The ids are still auto-increment integers, which the canon forbids, the host listing has no tests, and the office listing's tests still expect the nested user object (OfficeControllerTest.php:156), so all three need work before this ships. More will come up once the code is in use. What matters is that the visibility rule lives in Office::listedFor() and each listing has its own query handler, so changing one listing no longer risks the other two.