Skip to content
Back to home

CODING FINDS

Notes from the terminal.

Short write-ups of things I learned the hard way: the problem, the fix and the result, with the smallest snippet that shows it.

FOR CODING AGENTS

Every note is also available over MCP, so your coding agent can look up a fix before it writes the bug.

[MCP server URL]
All notes
Laravel

Let your DTOs turn themselves into arrays

Problem. DTOs keep data typed inside the app, but every endpoint that returns them has to turn them back into arrays first. The same map() with the same keys gets copied into each controller, and the copies drift apart: one endpoint sends price, another sends price_in_cents.

Fix. Implement Illuminate\Contracts\Support\Arrayable and give the DTO a toArray() method. Laravel looks for this contract wherever it turns data into output: a collection's toArray() and its JSON encoding convert every Arrayable item, and a controller can return a DTO, or a collection of them, to get a JSON response.

php
// Before: the same mapping in every controllerreturn response()->json(    collect($quotes)->map(fn (ShippingQuote $quote) => [        'carrier' => $quote->carrier,        'price' => $quote->priceInCents,        'days' => $quote->deliveryDays,    ]));// After: the DTO owns its array shape/** * @implements Arrayable<string, string|int> */final readonly class ShippingQuote implements Arrayable{    public function __construct(        public string $carrier,        public int $priceInCents,        public int $deliveryDays,    ) {}    public function toArray(): array    {        return [            'carrier' => $this->carrier,            'price' => $this->priceInCents,            'days' => $this->deliveryDays,        ];    }}// Each quote is converted for youreturn collect($quotes);

Result. The response shape lives in one place, next to the data it describes, and every endpoint stays in step. Arrayable is a generic interface, so the @implements line tells PHPStan which keys and values to expect. If you also call json_encode() on a DTO yourself, implement JsonSerializable as well: plain json_encode() ignores toArray(), while Laravel's collections and responses understand Arrayable on its own.

Stuck on something like this?

Tell me what you are working on. I’ll help you find it, fix it and keep it fixed.

Book a call