Lesson 22 of 22 · Conclusion
Laravel Console Commands: The Second Caller Ships
The introduction opened on ReservationController::store() and the question of how to call it from an Artisan command. Here is that Artisan command. ImportChannelReservationsCommand is a console class that Artisan runs; the bus never sees it.
The command and the job
The console command does one thing: it queues the job. The nightly scheduler calls it, and so can a staff member from a terminal when the channel manager resends a batch.
<?php
declare(strict_types=1);
namespace App\Reservations\ImportChannelReservations;
use Illuminate\Console\Command;
use Illuminate\Contracts\Bus\Dispatcher;
final class ImportChannelReservationsCommand extends Command
{
protected $signature = 'reservations:import-channel';
protected $description = 'Queue the import of reservations from the channel manager.';
public function handle(Dispatcher $bus): int
{
$bus->dispatch(new ImportChannelReservationsJob());
$this->info('Channel import queued.');
return self::SUCCESS;
}
}The job, which the DTO lesson started, talks to the channel manager through ChannelFeed, builds the same RequestReservationCommand the web controller builds, and dispatches it to the same handler:
<?php
declare(strict_types=1);
namespace App\Reservations\ImportChannelReservations;
use App\Guests\Guest\Guest;
use App\Reservations\RequestReservation\RequestReservationCommand;
use App\Reservations\Reservation\DateRange;
use App\Reservations\Reservation\GuestCount;
use App\Rooms\Room\Room;
use App\Shared\QueueName;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use InvalidArgumentException;
use Psr\Log\LoggerInterface;
final class ImportChannelReservationsJob implements ShouldQueue
{
use Queueable;
public int $tries = 3;
public int $backoff = 120;
public function __construct()
{
$this->queue = QueueName::IMPORTS->value;
}
public function handle(ChannelFeed $feed, Dispatcher $bus, LoggerInterface $logger): void
{
foreach ($feed->rows() as $row) {
try {
$stayDates = DateRange::fromStrings($row->arrival, $row->departure);
$guestCount = new GuestCount($row->adults, $row->children);
$room = Room::query()->where('number', $row->roomNumber)->firstOrFail();
$guest = Guest::query()->firstOrCreate(
['email' => $row->guestEmail],
['name' => $row->guestName, 'phone' => $row->guestPhone],
);
$result = $bus->dispatch(new RequestReservationCommand(
guestId: $guest->id,
roomId: $room->id,
stayDates: $stayDates,
guestCount: $guestCount,
));
$logger->info('Channel reservation imported', [
'reference' => $row->reference,
'reservation_id' => $result->reservationId,
]);
} catch (InvalidArgumentException|ModelNotFoundException $exception) {
$logger->warning('Channel row rejected', [
'reference' => $row->reference,
'reason' => $exception->getMessage(),
]);
}
}
}
}QueueName is new: a small backed enum in App\Shared, so no job names its queue with a raw string. It has one case, because the confirmation mail stays on the default queue. Run a worker for both queues with php artisan queue:work --queue=imports,default:
<?php
declare(strict_types=1);
namespace App\Shared;
enum QueueName: string
{
case IMPORTS = 'imports';
}The catch skips rows the property cannot take. A row with reversed dates or zero adults throws from the value object constructor, and a row with an unknown room number throws ModelNotFoundException. Both are built before the guest lookup, so a rejected row creates no guest. The job logs it with the channel's reference and moves to the next row, and the batch finishes. $tries and $backoff are explicit because the job talks to an external system: when the channel manager is down, the job retries twice, two minutes apart, and then lands in the failed jobs table with the exception attached. The job is not idempotent yet: a retry re-imports the rows it already wrote. Storing the channel's reference and skipping references already seen is the next step.
ChannelReservationRow::fromPayload() runs inside the feed before the loop starts, so a payload that breaks the channel's contract, such as a missing key or an unparseable date, stops the import, while a reservation the property cannot take is logged and skipped.
The HTTP implementation is the one class in the module that knows the channel manager's URL and credentials. Nothing else in the job mentions HTTP:
<?php
declare(strict_types=1);
namespace App\Reservations\ImportChannelReservations;
use Illuminate\Http\Client\Factory;
final readonly class HttpChannelFeed implements ChannelFeed
{
public function __construct(
private Factory $http,
private string $url,
private string $token,
) {}
/**
* @return iterable<int, ChannelReservationRow>
*/
public function rows(): iterable
{
$payloads = $this->http
->withToken($this->token)
->get($this->url)
->throw()
->json();
return array_map(ChannelReservationRow::fromPayload(...), $payloads);
}
}ReservationsServiceProvider gains two pieces of wiring. register() binds ChannelFeed to HttpChannelFeed. boot() registers the console command, because Laravel only discovers commands under app/Console/Commands and this one lives in the module:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Models\User;
use App\Reservations\CancelReservation\CancelReservationCommand;
use App\Reservations\CancelReservation\CancelReservationCommandHandler;
use App\Reservations\ChangeReservationDates\ChangeReservationDatesCommand;
use App\Reservations\ChangeReservationDates\ChangeReservationDatesCommandHandler;
use App\Reservations\CheckInGuest\CheckInGuestCommand;
use App\Reservations\CheckInGuest\CheckInGuestCommandHandler;
use App\Reservations\ImportChannelReservations\ChannelFeed;
use App\Reservations\ImportChannelReservations\HttpChannelFeed;
use App\Reservations\ImportChannelReservations\ImportChannelReservationsCommand;
use App\Reservations\ListReservations\ListReservationsQuery;
use App\Reservations\ListReservations\ListReservationsQueryHandler;
use App\Reservations\RequestReservation\RequestReservationCommand;
use App\Reservations\RequestReservation\RequestReservationCommandHandler;
use App\Reservations\RequestReservation\ReservationConfirmed;
use Illuminate\Http\Client\Factory;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
final class ReservationsServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(ChannelFeed::class, fn (): HttpChannelFeed => new HttpChannelFeed(
$this->app->make(Factory::class),
config('services.channel_manager.url'),
config('services.channel_manager.token'),
));
}
public function boot(): void
{
Bus::map([
RequestReservationCommand::class => RequestReservationCommandHandler::class,
ListReservationsQuery::class => ListReservationsQueryHandler::class,
CancelReservationCommand::class => CancelReservationCommandHandler::class,
CheckInGuestCommand::class => CheckInGuestCommandHandler::class,
ChangeReservationDatesCommand::class => ChangeReservationDatesCommandHandler::class,
]);
Gate::define('check-in-guests', fn (User $user): bool => (bool) $user->is_staff);
Event::listen(ReservationConfirmed::class, SendReservationConfirmation::class);
$this->loadRoutesFrom(__DIR__.'/reservations-routes.php');
$this->commands([ImportChannelReservationsCommand::class]);
}
}The two keys go in config/services.php as 'channel_manager' => ['url' => env('CHANNEL_MANAGER_URL'), 'token' => env('CHANNEL_MANAGER_TOKEN')]. routes/console.php schedules the command with Schedule::command('reservations:import-channel')->dailyAt('02:00');.
Read the job against the introduction's store(). It has no Auth::user(), because the command takes a guest id, and no inline validation, because DateRange and GuestCount carry the rules. Confirmation is a listener on ReservationConfirmed, the handler writes once, and nothing builds a fake Request, because the handler never needed one.
The test that was impossible
This is the test the introduction could not write. It builds the command directly, runs the handler, and checks the row and the event, with no HTTP request anywhere:
<?php
declare(strict_types=1);
namespace Tests\Feature\Reservations;
use App\Guests\Guest\Guest;
use App\Reservations\Reservation\DateRange;
use App\Reservations\Reservation\GuestCount;
use App\Reservations\Reservation\Reservation;
use App\Reservations\Reservation\ReservationStatus;
use App\Reservations\RequestReservation\RequestReservationCommand;
use App\Reservations\RequestReservation\RequestReservationCommandHandler;
use App\Reservations\RequestReservation\ReservationConfirmed;
use App\Rooms\Room\Room;
use App\Rooms\RoomType\RoomType;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;
final class RequestReservationCommandHandlerTest extends TestCase
{
use RefreshDatabase;
public function test_it_requests_a_reservation_without_http(): void
{
Event::fake([ReservationConfirmed::class]);
$guest = Guest::factory()->create();
$roomType = RoomType::factory()->create(['nightly_rate_cents' => 12000, 'currency' => 'EUR']);
$room = Room::factory()->for($roomType)->create();
$handler = $this->app->make(RequestReservationCommandHandler::class);
$result = $handler->handle(new RequestReservationCommand(
guestId: $guest->id,
roomId: $room->id,
stayDates: DateRange::fromStrings('2026-11-02', '2026-11-09'),
guestCount: new GuestCount(adults: 2, children: 1),
));
$this->assertSame(75600, $result->total->amount);
$this->assertSame('EUR', $result->total->currency);
$reservation = Reservation::query()->findOrFail($result->reservationId);
$this->assertSame(ReservationStatus::CONFIRMED, $reservation->status);
$this->assertSame($guest->id, $reservation->guest_id);
$this->assertSame(2, $reservation->adults);
Event::assertDispatched(
ReservationConfirmed::class,
fn (ReservationConfirmed $event): bool => $event->reservationId === $result->reservationId,
);
}
}Seven nights at 120.00 is 840.00, and the week-or-longer discount brings it to 756.00. The test knows that because NightlyRatePricingTest already pinned the rule; this test checks the handler wired the rule to the row. Event::fake() swaps the dispatcher the handler receives through its constructor, so assertDispatched sees the event without a listener running and without a mail being queued.
The web controller's feature test and the import job's test both call the same handler this test covers. Neither of them needs to re-test pricing, the write, or the event.
Then and now
Then | Now |
|---|---|
|
|
|
|
| Deleted when the reservation write collapsed to one save |
|
|
|
|
|
|
|
|
The import took a console command, a job, and a feed, because everything else it needed already existed with a signature it could call.
The one thing to remember
Write the first caller as if the second one is already waiting: a use case that takes typed values and returns typed values, with the framework kept at the edges. Then the second caller is a job class.
Related Links
- Why Your Laravel App Is Slowthe Queries and Data Access chapter as one article: repeated writes per request, $with on the model, queries inside accessors, Eloquent for reporting, SELECT *, and filtering in PHP.
- Why Your Laravel Codebase Is Unmaintainablethe Architecture and Code Organization chapter as one article: one controller calling another, Auth::user() in services, business logic in traits, files that never get split, the default folder structure, app() instead of constructor injection, and MVC treated as the architecture.
- Stop Writing Laravel APIs Like Thisthe Request Handling and API Design chapter as one article: $request->validated() into models, trusting the request, one endpoint with many intents, and one Form Request for create and update.
- Your Laravel Code Needs More Objectsthe Primitives and Value Objects chapter as one article: arrays as data bags, Eloquent everywhere, and primitives where objects belong, with billing examples instead of reservations.