Your Laravel Code Needs More Objects
Introduction
PHP lets you get away with arrays and raw strings forever. You ship a feature with a loose ['user_id' => ..., 'plan' => ...], it works, tests pass, you move on. A few features later you cannot tell what shape any method takes without reading the methods it calls.
The framework does not push back. Laravel accepts arrays, magic properties, and Eloquent models passed through every layer, and each of those is convenient on the day you write it. The cost lands on the day someone changes a key, a column, or a format and nothing tells them who else depended on it.
This is the value-objects deep dive from Top 20 Mistakes Laravel Developers Make. Three habits, one fix: name the concept, give it a class, and put its rules inside the class. The Laravel Best Practices: Writing Laravel That Lasts course walks the same three fixes through one codebase in its Primitives and Value Objects chapter; this article covers them with a billing example so you can read it on its own.
1. Arrays as data bags
A controller collects the request into an array and hands the same array to three collaborators:
<?php
declare(strict_types=1);
namespace App\Billing;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
final readonly class SubscribeController
{
public function __construct(
private Payments $payments,
private Subscriptions $subscriptions,
private WelcomeMailer $mailer,
) {
}
public function __invoke(Request $request): JsonResponse
{
$data = [
'user_id' => $request->integer('user_id'),
'email' => $request->string('email')->toString(),
'plan' => $request->string('plan')->toString(),
'amount' => $request->integer('amount'),
'currency' => $request->string('currency')->toString(),
];
$this->payments->charge($data);
$this->subscriptions->start($data);
$this->mailer->send($data);
return new JsonResponse(status: 202);
}
}Payments and Subscriptions are interfaces with one method each, and both take array $data. The mailer reads the same keys, so here it is in full:
<?php
declare(strict_types=1);
namespace App\Billing;
use Illuminate\Contracts\Mail\Mailer;
final readonly class WelcomeMailer
{
public function __construct(
private Mailer $mailer,
) {
}
/**
* @param array<string, mixed> $data
*/
public function send(array $data): void
{
$this->mailer->raw(
sprintf('Your %s plan costs %.2f %s per month.', $data['plan'], $data['amount'] / 100, $data['currency']),
fn ($message) => $message->to($data['email'])->subject('Welcome'),
);
}
}It runs until someone renames amount to amount_cents in the controller and the payments code, because the value is cents and the old name kept causing off-by-a-hundred bugs. The subscriptions code still reads amount. The mailer still reads amount. Nothing flags the stale reads before the code runs. On the first request PHP raises Undefined array key "amount", Laravel turns the warning into an ErrorException, and by then charge() has taken the customer's money while start() never finished.
An array used this way has no type and no contract. Every consumer guesses at the shape, and a key changed in one place breaks the others only when a request reaches them.
The fix is a DTO, short for data transfer object: a small class whose only job is to carry named, typed fields between layers.
<?php
declare(strict_types=1);
namespace App\Billing;
final readonly class SubscribeToPlanData
{
public function __construct(
public int $userId,
public string $email,
public string $plan,
public int $amountInCents,
public string $currency,
) {
}
}Once the DTO names the shape, the Form Request should too:
<?php
declare(strict_types=1);
namespace App\Billing;
use Illuminate\Foundation\Http\FormRequest;
final class SubscribeToPlanRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
/**
* @return array<string, list<string>>
*/
public function rules(): array
{
return [
'email' => ['required', 'email'],
'plan' => ['required', 'string', 'in:starter,team,business'],
'amount_cents' => ['required', 'integer', 'min:0'],
'currency' => ['required', 'string', 'size:3'],
];
}
}The controller builds one DTO and hands it on. $request->string() returns a Stringable, so the call to toString() is what makes the value a string the constructor accepts under strict types.
<?php
declare(strict_types=1);
namespace App\Billing;
use Illuminate\Http\JsonResponse;
final readonly class SubscribeController
{
public function __construct(
private Payments $payments,
private Subscriptions $subscriptions,
private WelcomeMailer $mailer,
) {
}
public function __invoke(SubscribeToPlanRequest $request): JsonResponse
{
$data = new SubscribeToPlanData(
userId: $request->user()->id,
email: $request->string('email')->toString(),
plan: $request->string('plan')->toString(),
amountInCents: $request->integer('amount_cents'),
currency: $request->string('currency')->toString(),
);
$this->payments->charge($data);
$this->subscriptions->start($data);
$this->mailer->send($data);
return new JsonResponse(status: 202);
}
}Payments and Subscriptions now take SubscribeToPlanData in place of array $data, and the mailer reads properties instead of keys:
<?php
declare(strict_types=1);
namespace App\Billing;
use Illuminate\Contracts\Mail\Mailer;
final readonly class WelcomeMailer
{
public function __construct(
private Mailer $mailer,
) {
}
public function send(SubscribeToPlanData $data): void
{
$this->mailer->raw(
sprintf('Your %s plan costs %.2f %s per month.', $data->plan, $data->amountInCents / 100, $data->currency),
fn ($message) => $message->to($data->email)->subject('Welcome'),
);
}
}Rename amountInCents now and every consumer breaks at once. The IDE and PHPStan point at the lines before the code runs, and a caller that still uses the old name fails on construction instead of passing the wrong shape through.
If two methods pass the same array around, you already have a DTO. You just have not written the class yet. Lesson Laravel DTOs Instead of Arrays for Everything does this refactor on the course codebase.
2. Eloquent everywhere
This one is subtle because Laravel makes it effortless. You type-hint a model in the controller, pass it to a service, which passes it to a mailer, which passes it to a job. The model travels through the whole stack:
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use Illuminate\Http\JsonResponse;
final readonly class CancelSubscriptionController
{
public function __construct(
private CancellationService $cancellations,
private CancellationMailer $mailer,
) {
}
public function __invoke(Subscription $subscription): JsonResponse
{
$this->cancellations->cancel($subscription);
$this->mailer->send($subscription);
CancellationWebhookJob::dispatch($subscription);
return new JsonResponse(status: 202);
}
}The service and the mailer both take the model. The job is the one to look at:
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Http\Client\Factory;
use Illuminate\Queue\SerializesModels;
final class CancellationWebhookJob implements ShouldQueue
{
use Dispatchable;
use Queueable;
use SerializesModels;
public function __construct(
public Subscription $subscription,
) {
}
public function handle(Factory $http): void
{
$http->post('https://partner.example/webhooks/cancelled', $this->subscription->toArray());
}
}Every layer now depends on the table. The mailer reaches for $subscription->user->email, so testing it needs a database with a subscription row and a user row. The webhook posts toArray(), so every column ships to the partner, including stripe_customer_id and the soft-delete timestamp. And the job does not carry the subscription at all. SerializesModels stores the model's class and key when the job is queued and loads the row again with firstOrFail() when the worker runs it. If the row changed in between, the job sees the new state, and if the row was deleted, the job fails with a ModelNotFoundException.
Keep Eloquent at the persistence boundary. A command goes in, a DTO comes out. The controller turns the request into a command, a small class named after the one action it asks for. One handler, the class that carries out that command, loads the model, does the work, and builds a DTO with the fields the rest of the system needs. Mail and webhooks consume the DTO and never see the model.
The command is the input shape:
<?php
declare(strict_types=1);
namespace App\Subscriptions;
final readonly class CancelSubscriptionCommand
{
public function __construct(
public int $subscriptionId,
public int $cancelledByUserId,
public string $reason,
) {
}
}The notice is the output shape:
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use Carbon\CarbonImmutable;
final readonly class CancellationNotice
{
public function __construct(
public int $subscriptionId,
public string $customerName,
public string $customerEmail,
public string $planName,
public CarbonImmutable $effectiveDate,
) {
}
}The Form Request checks the reason:
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use Illuminate\Foundation\Http\FormRequest;
final class CancelSubscriptionRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
/**
* @return array<string, list<string>>
*/
public function rules(): array
{
return [
'reason' => ['required', 'string', 'max:500'],
];
}
}The controller takes a plain id, builds the command, and dispatches it through Laravel's command bus, which finds the handler for the command and calls it:
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Http\JsonResponse;
final readonly class CancelSubscriptionController
{
public function __construct(
private Dispatcher $bus,
) {
}
public function __invoke(int $subscriptionId, CancelSubscriptionRequest $request): JsonResponse
{
$this->bus->dispatch(new CancelSubscriptionCommand(
subscriptionId: $subscriptionId,
cancelledByUserId: $request->user()->id,
reason: $request->string('reason')->toString(),
));
return new JsonResponse(status: 204);
}
}The rule about what cancelling means lives on the model, because the model owns the columns the rule reads:
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use App\Models\Plan;
use App\Models\User;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
final class Subscription extends Model
{
protected function casts(): array
{
return [
'cancelled_at' => 'immutable_datetime',
];
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function plan(): BelongsTo
{
return $this->belongsTo(Plan::class);
}
public function cancel(string $reason, int $cancelledByUserId, CarbonImmutable $cancelledAt): void
{
if ($this->cancelled_at !== null) {
throw new SubscriptionAlreadyCancelled($this->id);
}
$this->cancellation_reason = $reason;
$this->cancelled_by = $cancelledByUserId;
$this->cancelled_at = $cancelledAt;
$this->save();
}
}The exception renders itself, so no controller has to catch it:
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use Illuminate\Http\JsonResponse;
use RuntimeException;
final class SubscriptionAlreadyCancelled extends RuntimeException
{
public function __construct(int $subscriptionId)
{
parent::__construct("Subscription {$subscriptionId} is already cancelled.");
}
public function render(): JsonResponse
{
return new JsonResponse(['message' => $this->getMessage()], 409);
}
}The handler is the only class that sees the model. It loads exactly the relations the notice needs, calls the model method, builds the notice, and announces what happened:
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\Events\Dispatcher;
final readonly class CancelSubscriptionCommandHandler
{
public function __construct(
private Dispatcher $events,
) {
}
public function handle(CancelSubscriptionCommand $command): void
{
$now = CarbonImmutable::now();
$subscription = Subscription::query()
->with(['user', 'plan'])
->findOrFail($command->subscriptionId);
$subscription->cancel(
reason: $command->reason,
cancelledByUserId: $command->cancelledByUserId,
cancelledAt: $now,
);
$this->events->dispatch(new SubscriptionCancelled(new CancellationNotice(
subscriptionId: $subscription->id,
customerName: $subscription->user->name,
customerEmail: $subscription->user->email,
planName: $subscription->plan->name,
effectiveDate: $now->endOfMonth(),
)));
}
}The event carries the notice. A queued listener that received the model through an event using SerializesModels (the make:event default) would get it reloaded from the database when the job runs, so it would see whatever the row looks like then. The notice is a snapshot of the moment the cancellation happened.
<?php
declare(strict_types=1);
namespace App\Subscriptions;
final readonly class SubscriptionCancelled
{
public function __construct(
public CancellationNotice $notice,
) {
}
}The listener sends the mail and queues the webhook. Both get the notice:
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Contracts\Mail\Mailer;
final readonly class SendCancellationNotice
{
public function __construct(
private Mailer $mailer,
private Dispatcher $bus,
) {
}
public function handle(SubscriptionCancelled $event): void
{
$this->mailer
->to($event->notice->customerEmail)
->send(new CancellationConfirmation($event->notice));
$this->bus->dispatch(new SendCancellationWebhook($event->notice));
}
}The handler and the listener run only once a service provider wires them: the bus does not know which handler goes with the command, and event discovery only scans app/Listeners. Register the provider in bootstrap/providers.php:
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
final class SubscriptionsServiceProvider extends ServiceProvider
{
public function boot(): void
{
Bus::map([
CancelSubscriptionCommand::class => CancelSubscriptionCommandHandler::class,
]);
Event::listen(SubscriptionCancelled::class, SendCancellationNotice::class);
}
}The mailable renders from the notice:
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
final class CancellationConfirmation extends Mailable implements ShouldQueue
{
public function __construct(
public CancellationNotice $notice,
) {
}
public function envelope(): Envelope
{
return new Envelope(subject: 'Your subscription has been cancelled');
}
public function content(): Content
{
return new Content(
markdown: 'mail.subscriptions.cancelled',
with: [
'name' => $this->notice->customerName,
'plan' => $this->notice->planName,
'effectiveDate' => $this->notice->effectiveDate->toFormattedDateString(),
],
);
}
}And the webhook job posts the notice's fields, nothing else:
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Http\Client\Factory;
final class SendCancellationWebhook implements ShouldQueue
{
use Queueable;
public int $tries = 3;
public int $backoff = 60;
public function __construct(
public CancellationNotice $notice,
) {
}
public function handle(Factory $http): void
{
$http->post('https://partner.example/webhooks/cancelled', [
'subscription_id' => $this->notice->subscriptionId,
'plan' => $this->notice->planName,
'effective_date' => $this->notice->effectiveDate->toIso8601String(),
]);
}
}The mailable's test runs with a CancellationNotice built in the test method and no database. The webhook payload is the notice's shape, so stripe_customer_id never leaves the building. The table can gain or rename a column and the mail and the webhook do not notice.
Lesson Laravel Queued Mailables That Carry Eloquent Models applies this to a queued mailable and a pricing class.
3. Primitives where objects belong
Every codebase I've reviewed has a cluster of strings and ints that look innocent and are not:
<?php
declare(strict_types=1);
namespace App\Billing;
interface PaymentGateway
{
public function charge(
string $email,
int $amountInCents,
string $currency,
string $countryCode,
): void;
}$email could be "not an email". $currency could be "usd" or "USD" or "dollars". $countryCode could be two letters, three letters, or a full country name, depending on which developer touched it last. $amountInCents could be a dollar amount at the one call site that forgot to multiply by 100.
The checks for each of these live wherever someone last needed them: a Form Request rule here, an if in a handler there, a helper in App\Support. When a rule changes you either find every copy or accept that they drift.
A value object puts the rule where the type lives. It wraps a value, checks it in the constructor, and carries the behaviour that belongs to the concept. Email refuses to exist with an invalid address and knows how to give you its domain:
<?php
declare(strict_types=1);
namespace App\Shared;
use InvalidArgumentException;
final readonly class Email
{
public function __construct(public string $value)
{
if (! filter_var($value, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException("Invalid email: {$value}");
}
}
public function domain(): string
{
return substr($this->value, strpos($this->value, '@') + 1);
}
}Money refuses negative amounts and refuses to add two currencies together. The currency check here is shape only: three uppercase letters. A real ISO 4217 check needs the list of codes, which is what the moneyphp/money package carries, so reach for that once you need it.
<?php
declare(strict_types=1);
namespace App\Shared;
use InvalidArgumentException;
final readonly class Money
{
public function __construct(
public int $amountInCents,
public string $currency,
) {
if ($amountInCents < 0) {
throw new InvalidArgumentException('Money cannot be negative.');
}
if (preg_match('/^[A-Z]{3}$/', $currency) !== 1) {
throw new InvalidArgumentException("Currency must be three uppercase letters: {$currency}");
}
}
public function add(Money $other): self
{
if ($other->currency !== $this->currency) {
throw new InvalidArgumentException('Currency mismatch.');
}
return new self($this->amountInCents + $other->amountInCents, $this->currency);
}
}CountryCode pins the format to ISO 3166-1 alpha-2 and carries the one question the billing code keeps asking about countries:
<?php
declare(strict_types=1);
namespace App\Shared;
use InvalidArgumentException;
final readonly class CountryCode
{
private const EU_MEMBERS = [
'AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR',
'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL',
'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE',
];
public function __construct(public string $value)
{
if (preg_match('/^[A-Z]{2}$/', $value) !== 1) {
throw new InvalidArgumentException("Country code must be ISO 3166-1 alpha-2: {$value}");
}
}
public function isEuMember(): bool
{
return in_array($this->value, self::EU_MEMBERS, true);
}
}The signature now tells the truth:
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Shared\CountryCode;
use App\Shared\Email;
use App\Shared\Money;
interface PaymentGateway
{
public function charge(Email $email, Money $price, CountryCode $country): void;
}An invalid Email cannot exist. A negative Money cannot exist. A currency mismatch throws at the line that made the mistake instead of three classes downstream. Behaviour attaches to the type: $price->add($tax), $email->domain(), $country->isEuMember().
This also feeds back into section 1. SubscribeToPlanData carried int $amountInCents and string $currency as two fields that only make sense together. Replace them with one Money $price and the DTO can no longer be built with a negative amount or a lowercase currency.
Lesson Laravel Value Objects Instead of Primitives builds DateRange, GuestCount, and Money for a reservation system.
Where to start in an existing codebase
Introduce the three in the order the code pulls you. Start at the controller: the next time you build an array to pass along, build a DTO instead, and let the array-reading collaborators take the DTO one at a time. The DTO's fields then show you which value objects are missing, because two fields that only make sense together, or one field with a check in its consumers, are a value object waiting to be written. The model boundary comes last, once a handler exists to own the load-and-mutate step, because until then there is no natural place to build the outgoing DTO.
Related Links
- Top 20 Mistakes Laravel Developers Makethe pillar index this deep dive sits under
- Laravel Best Practices: Writing Laravel That Laststhe course; its Primitives and Value Objects chapter applies these three fixes to one reservation codebase
- Why Your Laravel App Is Slowmultiple writes per use case, eager loading on the model, queries in accessors, reporting through Eloquent, SELECT *, and filtering in PHP
- Why Your Laravel Codebase Is Unmaintainablecontrollers calling controllers, Auth::user() in services, business rules in traits, files that never split, the default folder structure, service location, and MVC as the architecture
- Stop Writing Laravel APIs Like Thisvalidated() into models, raw request values, one endpoint with many intents, and one Form Request for create and update