Laravel Clean Code (2)

Ali Heydari
2 min readSep 4, 2022

--

In the first part of clean coding in Laravel, we learned about 5 interesting tips for writing clean and readable code. In this section, we will share the second point with you. Do not forget that these items are in no order or priority and each can be important in its place.

6. Using the Repository at the right time

If you use Query Builder or raw SQL queries and have very large models and long controllers, it is better to put all the logic related to the DB in Eloquent models or in Repository classes.

7. Use doc blocks (comment blocks) only when they clarify something obscure.

Many people will disagree with this because they do it. But there is no point in using doc blocks if they don’t provide additional information. If the type hint is sufficient, there’s no need for an extra doc block because it just messes up the code.

8. Comments usually indicate poor code design

Before writing a comment, ask yourself if you can rename some things or create variables to improve readability. If this is not possible, write the comment in such a way that both your colleagues and you will notice 6 months later.

9. Do not write only procedural code in classes

OOP is there to make your code more readable, use it. Do not write only 400 lines of procedural code in controller actions.

10. Try to use only CRUD actions

If you can, use only 7 CRUD actions in your controllers. Even less. Don’t create a controller with 20 methods. Shorter controllers are better.

Each of the mentioned points, if used in the right place, will make us have a cleaner and more readable code. Also, fully understanding and applying them will make you a better developer. But clean coding tips are not limited to these things and we have explained more tips in the third part of this article.

--

--

No responses yet