logo
podcast Podcast
get help Get Unstuck

Better types in API resources

And very simple to do

Joel Clermont
Joel Clermont
2024-09-16

Recently, I submitted a pull request on a project that included a new API resource.

Here's a simplified version of what it looked like:

class NoteResource extends JsonResource
 {
     /**
      * @return array<string, mixed>
      */
     public function toArray(Request $request): array
     {
         /** @var Note $note */
         $note = $this->resource;

         return [
             'id' => $note->id,
             'parent_id' => $note->parent_id,
             'parent_type' => $note->parent_type,
             'note' => $note->note,
             'type' => $note->type,
         ];
     }
 }

One question on the review was "Why are you assigning the resource to a variable?"

It's true, I could have just used $this->resource directly when defining my array to return, but I'd be missing out on some tooling benefits.

By assigning the resource to a variable, I can also assign the model as a type to that resource.

In my editor, I now get nice auto-complete and syntax highlighting for $note and all its properties.

And static analysis tools, like PHPStan, will be able to catch issues if I try to access a property that doesn't exist on the model.

In the future, if I do some refactoring on that model, it will extend to this resource automatically as well.

Quite a few nice benefits from a simple change.

Here to help,

Joel

P.S. Are you using PHPStan on your project yet? If not, we can get you started and help get over that initial learning curve. Get in touch if that sounds useful to you.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.