DEV Community

Yogesh Galav
Yogesh Galav

Posted on • Updated on

How to write clean code in Laravel?

Laravel is the most beautiful thing ever done to PHP. But most developers working in project based company like in India don't utilize it to make there strength. The best thing about it is predefined structure but of-course people break it bcoz any code written in core PHP works inside Laravel. I'm writing this blog to transfer my knowledge of writing clean code in Laravel hence making projects and products maintainable and beautiful.

Why clean code?

a. With clean code you can find your files and code faster, hence resulting into faster development.
b. Your code looks shorter hence easy to understand.
c. User experience become good with good code.
d. Debugging and updating of business logic takes less time.

1. Write Clean PHP
a. There are many rules for writing standard PHP code, I cannot list them all here hence just use tools which can fix your code.
b. Use PHP CodeSniffer, Use PHP-CS-Fixer, Use Laravel Pint or just use Duster package for Laravel.
c. Duster is a tool that brings together Laravel Pint, PHP CodeSniffer, PHP-CS-Fixer, and Tighten's Laravel-specific lints in Tlint to provide a powerful and comprehensive linting and fixing toolset for Laravel apps.
d. One programming hack I want to point it out here, Please don't use nested "If else". Instead use more "return" statements.

2. Write Clean Models
a. Models are the representation of database table in object format hence clean Model should only contain respective table information.
b. Model should tell us which are all the field present in table without looking in database by mentioning them Fillables.
c. Mention all the Relationships with other tables.
d. Use Mutators & Casting for formatting fields before using them.
e. Use Scopes for making eloquent queries short in respect to particular table.
f. Don't write any additional code like db queries or heavy functions. It will eventually deteriorate the quality of model.

3. Write Clean Views
a. Views are meant for better UX/UI and that can be done with better design, css, SPA, fast interaction with frontend logic.
It doesn't meant to carry all of your applications load.
b. For things which are not regularly used by user like deleting an item, why need to define it in frontend and backend both, sometimes dev do it in frontend alone, You can only handle it in backend.
c. If your entity has less data or is static why to get that data from backend? You can store, search and filter that data quickly in you frontend, why to bother backend. In case of data change, It will be less time taking and cheaper if you store all that in single constants file rather then database.
d. Use single master template and different layout templates for different user types. Keep Header, Sidebar and footer like component inside "includes" folder.
e. Don't call eloquent queries in blade files.
f. Keep folder structure exactly like url in pages folder even if you use frontend framework like vue or react so you can also use folder based routing.
g. Keep your JS at one place(resouces/js) and css at one place (resouces/sass).
h. Use single blade file in case of Vue SPA or Inerita.
i. If you are using some heavy library like moment, always use helpers or utils file as intermediatory file, don't import this heavy package directly in your component file. It will make huge impact on your bundle size.

4. Write Clean Controllers
a. Controller is the place where business logic resides and hence it's also the place where most of the mess take place
b. Keep validation logic separately in FormRequest classes. They are also simple to use and understand.
c. Keep function name simple as index, store, create, update, delete, download, search etc. Don't use random names like getUserData or saveUser. I know you will require different data set for particular entity or Model like getAdminUsers but you can just apply and extra if to your index function and that's it.
d. If a particular function like index fetches two or more items it's ideal to make child functions which you can declare in Helpers, Services, Actions, Jobs etc
In this case try to keep if-else and for-loop inside controller function only.
e. If the function doesn't use much code then it's ideal to use Models or DB query directly.
f. It's much efficient to use DB query for getting list or Index data and Eloquent for create, update, delete.
g. Don't use try catch everywhere. it's only useable in case of multiple insertion into database for rollback. Else let the error come in logs and fix it.
You can handle 500 error at frontend catch part, so why to catch it in backend? It will decrease your code coverage while writing test.
And if you do get error, then you always has to edit the code for finding that error in local, there's no way you will be editing backend on server, Will you?
h. Use Resource Classes for json output. Or atleast keep the format of response same everywhere. Don't send status like "status" or "success" or "error" in response body, it can be automatically determined by status code in response header.

I hope you enjoyed reading this.
Thankyou and have a nice day!

Top comments (0)