Laravel: using phpDoc to write more readable code

Image with some unreadable code by Markus Spiske on Unsplash

This article explains you on how to use phpDoc, to make your own Laravel code a more easy to read. I do note that some tips can also be applied for other PHP projects like Symfony, WordPress, Drupal but a bit differently.

If you been using Laravel for a while, you must know that Laravel Models uses a lot of magic methods like __get and __set. These are used to access your values, which has been fetched from your database.

You’ll notice the color and styling of the property email and the explanation “property accessed by magic method”. More importantly it is unclear which properties are available for the DB table “authors”.

Available database columns

You can easily add information to your models, by using phpDoc by adding comments with two asterisks (/**) to your model. Now you can start adding the existing column names and also the type of data.

Now you’ll notice that your IDE finally understands which database columns are available. In the background, the method __get will be called.
Which helps to access the properties that are mass-assignable or guarded.

  • Your code will become more readable
  • It explains your database structure
  • You get code highlighting
  • You can add meaningful comments to each property / column


You can also use these type of comments, to declare make navigating between relations more easy.

These comments helps you accessing the correct models, when you for example CMD-click tenant you’ll be eventually be forwarded to the model Tenant.

A one-to-one relation with belongsTo is very straightforward, but using comments for HasMany relations can help for accessing helper methods of a collection.

When you use a foreach, PhpStorm automatically detects that the variable $story is the model Story.

Accessors and mutators

You can also use comments to hint about your accessors and mutators by writing a method getFullNameAttribute for the user model.

That method will return the first name and last name concatenated.

You’ll notice that I am here using property-read instead of property, this tells your editor that it can only be read. Now let’s say you also want to set full_name with a mutator, you can simply replace property-read with property.

Then write the method setFullNameAttribute to handle setting the first name and lastname.

Now all these properties became explanatory and navigating between files happens faster and saves you a lot of time. Also, your new coworkers will think your code is easier to understand.

Senior back-end developer in Ghent who likes writing sometimes weird / creative solutions to a specific problem.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store