Laravel: PHPDocs for Models everyone should have

Your favorite IDE will pick them up and make your life easier

Photo by Rémi Walle on Unsplash

Builder Helpers

First and foremost, since all methods not in the model are passed down to a new Eloquent Builder instance, we need to use the @mixin statement and point to the Builder class. This tells our IDE that we can call the mixed class methods from this class.

Properties

One of the magics of the Eloquent ORM are dynamic properties, wich return null if these don’t exist.

Timestamps

If your model is using timestamps, it’s nice to also add them in the PHPDoc, specially if you work with them constantly. They’re safe to skip if you don’t deal with timestamps, but I do deal with them in some projects, like when you need to calculate the expiration from the creation time.

Accessors

The next section is separate from the normal properties since the list is not part of the table columns, but rather properties created dynamically for the model. Let’s use a simple example: the full name of the user.

Relations

Relations in Eloquent ORM can be accessed dynamically using the method name that declares it, like $user->posts for posts(), but you can’t set them like it were properties — for that you will need to use setRelation().

Local Scopes

Finally, you may need to setup some local scopes to avoid building cryptic queries instead of purposeful methods. Local scopes can be accessed from the outside without the scope prefix, so we can safely state a new method that returns a Builder instance or the model (in case we need to chain up another scope).

Wrap up

This is how the model looks like in the end. You’re free to edit the PHPDocs or copy-paste them into your project. I added these to Larawiz long time ago, so when I make small projects I don’t need to copy-paste them in every model.

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor.