Don't Read Auth::user() Inside a Use Case
RequestReservation writes Auth::user()->guest_id into the new row. In the browser that is the guest making the reservation. In an Artisan command or a queued job there is no session, so Auth::user() returns null and the first row throws. In the channel import it returns the staff member whose API token triggered the push, so every imported reservation is attached to that staff member's guest record instead of the guest named in the row. The signature says nothing about any of this.
Don't do this:
<?php
declare(strict_types=1);
namespace App\Services;
use App\Models\Reservation;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Auth;
final class RequestReservation
{
public function handle(int $roomId, CarbonImmutable $checkIn, CarbonImmutable $checkOut): Reservation
{
return Reservation::query()->create([
'guest_id' => Auth::user()->guest_id,
'room_id' => $roomId,
'check_in' => $checkIn,
'check_out' => $checkOut,
'status' => 'confirmed',
'confirmed_at' => CarbonImmutable::now(),
]);
}
}Do this instead
The use case writes a guest_id, so it takes the guest_id as an argument. The controller is the one place that knows there is a request and a session, so it reads the user.
<?php
declare(strict_types=1);
namespace App\Services;
use App\Models\Reservation;
use Carbon\CarbonImmutable;
final class RequestReservation
{
public function handle(
int $guestId,
int $roomId,
CarbonImmutable $checkIn,
CarbonImmutable $checkOut,
): Reservation {
return Reservation::query()->create([
'guest_id' => $guestId,
'room_id' => $roomId,
'check_in' => $checkIn,
'check_out' => $checkOut,
'status' => 'confirmed',
'confirmed_at' => CarbonImmutable::now(),
]);
}
}<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Services\RequestReservation;
use Carbon\CarbonImmutable;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
final class ReservationController extends Controller
{
public function store(Request $request, RequestReservation $requestReservation): RedirectResponse
{
$validated = $request->validate([
'room_id' => ['required', 'exists:rooms,id'],
'check_in' => ['required', 'date', 'after_or_equal:today'],
'check_out' => ['required', 'date', 'after:check_in'],
]);
$reservation = $requestReservation->handle(
guestId: (int) $request->user()->guest_id,
roomId: (int) $validated['room_id'],
checkIn: CarbonImmutable::parse($validated['check_in']),
checkOut: CarbonImmutable::parse($validated['check_out']),
);
return redirect()->route('reservations.show', $reservation);
}
}Each caller now answers "which guest?" in the only way it can: the browser from the session, the import from the row's own guest, a test from a factory. The use case asks the question in its signature, so a caller that forgets the id gets an ArgumentCountError from PHP instead of a reservation on the wrong guest. The same rule covers any value that exists only during a request, such as the request's IP address.