In this thread I'll list tactics you can use to write cleaner code in Laravel.
As you use them repeatedly, you'll develop a sense for what's good code and what's bad code.
I'll also sprinkle some general Laravel code advice in between these tactics.
THREAD
As you use them repeatedly, you'll develop a sense for what's good code and what's bad code.
I'll also sprinkle some general Laravel code advice in between these tactics.
THREAD
It's about the *micro*.
Using some "macro" philosophy for structuring your code, like hexagonal architecture or DDD won't save you.
A clean codebase is the result of constant good decisions at the micro level.
Using some "macro" philosophy for structuring your code, like hexagonal architecture or DDD won't save you.
A clean codebase is the result of constant good decisions at the micro level.
Instead of writing repetitive `else if` statements, use an array to look up the wanted value based on the key you have.
The code will be cleaner & more readable and you will see understandable exceptions if something goes wrong. No half-passing edge cases.
The code will be cleaner & more readable and you will see understandable exceptions if something goes wrong. No half-passing edge cases.
Try to avoid unnecessary nesting by returning a value early.
Too much nesting & else statements tend to make code harder to read.
Too much nesting & else statements tend to make code harder to read.
Don't split lines at random places, but don't make them too long either.
Opening an array with [ and indenting the values tends to work well. Same with long function parameter values.
Other good places to split lines are chained calls and closures.
Opening an array with [ and indenting the values tends to work well. Same with long function parameter values.
Other good places to split lines are chained calls and closures.
Create variables when they improve readability
The opposite of the previous tip. Sometimes the value comes from a complex call and as such, creating a variable improves readability & removes the need for a comment.
Remember that context matters & your end goal is readability
The opposite of the previous tip. Sometimes the value comes from a complex call and as such, creating a variable improves readability & removes the need for a comment.
Remember that context matters & your end goal is readability
Create model methods for business logic
Your controllers should be simple. They should say things like "create invoice for order". They shouldn't be concerned with the details of how your database is structured.
Leave that to the model.
Your controllers should be simple. They should say things like "create invoice for order". They shouldn't be concerned with the details of how your database is structured.
Leave that to the model.
Create action classes
Let's expand on the previous example. Sometimes, creating a class for a single action can clean things up.
Models should encapsulate the business logic related to them, but they shouldn't be too big.
Let's expand on the previous example. Sometimes, creating a class for a single action can clean things up.
Models should encapsulate the business logic related to them, but they shouldn't be too big.
Consider using form requests.
They're a great place to hide complex validation logic.
But beware of exactly that — hiding things. When your validation logic is simple, there's nothing wrong with doing it in the controller. Moving it to a form request makes it less explicit
They're a great place to hide complex validation logic.
But beware of exactly that — hiding things. When your validation logic is simple, there's nothing wrong with doing it in the controller. Moving it to a form request makes it less explicit
Use events.
Consider offloading some logic from controllers to events. For example, when creating models.
The benefit is that creating these models will work the same everywhere (controllers, jobs, ...) and the controller has one less worry about the details of the DB schema
Consider offloading some logic from controllers to events. For example, when creating models.
The benefit is that creating these models will work the same everywhere (controllers, jobs, ...) and the controller has one less worry about the details of the DB schema
Extract methods.
If some method is too long or complex, and it's hard to understand what exactly is happening, split the logic into multiple methods.
If some method is too long or complex, and it's hard to understand what exactly is happening, split the logic into multiple methods.
Create helper functions.
If you repeat some code a lot, consider if extracting it to a helper function would make the code cleaner.
If you repeat some code a lot, consider if extracting it to a helper function would make the code cleaner.
Avoid helper *classes*.
Sometimes people put helpers into a class.
Beware, it can get messy. This is a class with only static methods used as helper functions. It's usually better to put these methods into classes with related logic or just keep them as global functions.
Sometimes people put helpers into a class.
Beware, it can get messy. This is a class with only static methods used as helper functions. It's usually better to put these methods into classes with related logic or just keep them as global functions.
Dedicate a weekend towards learning proper OOP.
Know the difference between static/instance methods & variables and private/protected/public visibility. Also learn how Laravel uses magic methods.
You don't need this as a beginner, but as your code grows, it's crucial.
Know the difference between static/instance methods & variables and private/protected/public visibility. Also learn how Laravel uses magic methods.
You don't need this as a beginner, but as your code grows, it's crucial.
Don't just write procedural code in classes.
This ties the previous tweet with the other tips here. OOP exists to make your code more readable, use it. Don't just write 400 line long procedural code in controller actions.
Here's code from my first Laravel project
This ties the previous tweet with the other tips here. OOP exists to make your code more readable, use it. Don't just write 400 line long procedural code in controller actions.
Here's code from my first Laravel project
Read up on things like SRP & follow them to *reasonable* extent
Avoid having classes that deal with many unrelated things
But, for the love of god, don't create a class for every single thing. You're trying to write clean code. You're not trying to please the separation gods
Avoid having classes that deal with many unrelated things
But, for the love of god, don't create a class for every single thing. You're trying to write clean code. You're not trying to please the separation gods
When you see a function with a huge amount of parameters, it can mean:
1. The function has too many responsibilities. Separate.
2. The responsibilities are fine, but you should refactor the long signature.
Below are two tactics for the fixing second case.
1. The function has too many responsibilities. Separate.
2. The responsibilities are fine, but you should refactor the long signature.
Below are two tactics for the fixing second case.
Use Data Transfer Objects (DTOs).
Rather than passing a huge amount of arguments in a specific order, consider creating an object with properties to store this data.
Bonus points if you can find that some behavior can be moved into to this object.
Rather than passing a huge amount of arguments in a specific order, consider creating an object with properties to store this data.
Bonus points if you can find that some behavior can be moved into to this object.
Create fluent objects.
You can also create objects with fluent APIs. Gradually add data by with separate calls, and only require the absolute minimum in the constructor.
Each method will return $this, so you can stop at any call.
You can also create objects with fluent APIs. Gradually add data by with separate calls, and only require the absolute minimum in the constructor.
Each method will return $this, so you can stop at any call.
Use custom collections.
Creating custom collections can be a great way to achieve more expressive syntax. Consider this example with order totals.
Creating custom collections can be a great way to achieve more expressive syntax. Consider this example with order totals.
Don't use abbreviations.
Don't think that long variable/method names are wrong. They're not. They're expressive.
Better to call a longer method than a short one and check the docblock to understand what it does
Same with variables. Don't use nonsense 3-letters abbreviations
Don't think that long variable/method names are wrong. They're not. They're expressive.
Better to call a longer method than a short one and check the docblock to understand what it does
Same with variables. Don't use nonsense 3-letters abbreviations
Try to only use CRUD actions
If you can, only use the 7 CRUD actions in your controllers. Often even fewer.
Don't create controllers with 20 methods.
More shorter controllers is better.
If you can, only use the 7 CRUD actions in your controllers. Often even fewer.
Don't create controllers with 20 methods.
More shorter controllers is better.
Use expressive names for methods.
Rather than thinking "what can this object do", think about "what can be done with this object". Exceptions apply, such as with action classes, but this is a good rule of thumb.
Rather than thinking "what can this object do", think about "what can be done with this object". Exceptions apply, such as with action classes, but this is a good rule of thumb.
Create single-use traits
Adding methods to classes where they belong is cleaner than creating action classes for everything, but it can make the classes grow big
Consider using traits. They're meant *primarily* for code reuse, but there's nothing wrong with single-use traits
Adding methods to classes where they belong is cleaner than creating action classes for everything, but it can make the classes grow big
Consider using traits. They're meant *primarily* for code reuse, but there's nothing wrong with single-use traits
Create single-use Blade includes.
Similar to single-use traits.
This tactic is great when you have a very long template and you want to make it more manageable.
There's nothing wrong with @including headers and footers in layouts, or things like complex forms in page views.
Similar to single-use traits.
This tactic is great when you have a very long template and you want to make it more manageable.
There's nothing wrong with @including headers and footers in layouts, or things like complex forms in page views.
Import namespaces instead of using aliases
Sometimes you may have multiple classes with the same name. Rather than importing them with an alias, import the namespaces.
Sometimes you may have multiple classes with the same name. Rather than importing them with an alias, import the namespaces.
Create query scopes for complex where()s.
Rather than writing complex where() clauses, create query scopes with expressive names.
This will make your e.g. controllers have to know less about the database structure and your code will be cleaner.
Rather than writing complex where() clauses, create query scopes with expressive names.
This will make your e.g. controllers have to know less about the database structure and your code will be cleaner.
Don't use model methods to retrieve data
If you want to retrieve some data from a model, create an accessor.
Keep methods for things that *change* the model in some way.
If you want to retrieve some data from a model, create an accessor.
Keep methods for things that *change* the model in some way.
Use custom config files.
You can store things like "results per page" in config files. Don't add them to the app config file though. Create your own. In my e-commerce project, I use config/shop.php.
You can store things like "results per page" in config files. Don't add them to the app config file though. Create your own. In my e-commerce project, I use config/shop.php.
Don't use a controller namespace
Instead of writing controller actions like PostController@index, use the callable array syntax [PostController::class, 'index'].
You will be able to navigate to the class by clicking PostController.
Instead of writing controller actions like PostController@index, use the callable array syntax [PostController::class, 'index'].
You will be able to navigate to the class by clicking PostController.
Consider single-action controllers
If you have a complex route action, consider moving it to a separate controller.
For OrderController::create, you'd create CreateOrderController.
Another solution is to move that logic to an action class — do what works best in your case.
If you have a complex route action, consider moving it to a separate controller.
For OrderController::create, you'd create CreateOrderController.
Another solution is to move that logic to an action class — do what works best in your case.
Be friends with your IDE.
Install extensions, write annotations, use typehints. Your IDE will help you with getting your code working correctly, which lets you spend more energy on writing code that's also readable.
Install extensions, write annotations, use typehints. Your IDE will help you with getting your code working correctly, which lets you spend more energy on writing code that's also readable.
Decide if you like spaces around operators.
Above you can see that I use space between ! and the value I'm negating. I like this, because it makes it clear that the value is being negated. I do the same around dots.
Decide if you like it. It can (imo) clean up your code.
Above you can see that I use space between ! and the value I'm negating. I like this, because it makes it clear that the value is being negated. I do the same around dots.
Decide if you like it. It can (imo) clean up your code.
Consider using helpers instead of facades. They can clean things up.
This is largely a matter of personal preference, but calling a global function instead of having to import a class and statically call a method feels nicer to me.
Bonus points for session('key') syntax.
This is largely a matter of personal preference, but calling a global function instead of having to import a class and statically call a method feels nicer to me.
Bonus points for session('key') syntax.
Create custom Blade directives for business logic.
You can make your Blade templates more expressive by creating custom directives. For example, rather than checking if the user has the admin role, you could use @admin.
You can make your Blade templates more expressive by creating custom directives. For example, rather than checking if the user has the admin role, you could use @admin.
Avoid queries in Blade when possible
Sometimes you may want to execute DB queries in blade. There are some ok use cases for this, such as in layout files.
But if it's a view returned by a controller, pass the data in the view data instead.
Sometimes you may want to execute DB queries in blade. There are some ok use cases for this, such as in layout files.
But if it's a view returned by a controller, pass the data in the view data instead.
Use strict comparison.
ALWAYS use strict comparison (=== and !==). If needed, cast things go the correct type before comparing. Better than weird == results
Also consider enabling strict types in your code. This will prevent passing variables of wrong data types to functions
ALWAYS use strict comparison (=== and !==). If needed, cast things go the correct type before comparing. Better than weird == results
Also consider enabling strict types in your code. This will prevent passing variables of wrong data types to functions
Use docblocks only when they clarify things.
Many people will disagree with this, because they do it. But it makes no sense.
There's no point in using docblocks when they don't give any extra information. If the typehint is enough, don't add a docblock.
That's just noise.
Many people will disagree with this, because they do it. But it makes no sense.
There's no point in using docblocks when they don't give any extra information. If the typehint is enough, don't add a docblock.
That's just noise.
Have a single source of truth for validation rules.
If you validate some resource's attributes on multiple places, you definitely want to centralize these validation rules, so that you don't change them in one place but forget about the other places. https://twitter.com/LiamHammett/status/1260252814158282752
If you validate some resource's attributes on multiple places, you definitely want to centralize these validation rules, so that you don't change them in one place but forget about the other places. https://twitter.com/LiamHammett/status/1260252814158282752
Use collections when they can clean up your code.
Don't turn all arrays into collections just because Laravel offers them, but DO turn arrays into collections when you can make use of collection syntax to clean up your code.
Don't turn all arrays into collections just because Laravel offers them, but DO turn arrays into collections when you can make use of collection syntax to clean up your code.
Write functional code when it benefits you.
Functional code can both clean things up and make them impossible to understand. Refactor common loops into functional calls, but don't write stupidly complex reduce()s just to avoid writing a loop. There's a use case for both.
Functional code can both clean things up and make them impossible to understand. Refactor common loops into functional calls, but don't write stupidly complex reduce()s just to avoid writing a loop. There's a use case for both.
Comments usually indicate poor code design.
Before writing a comment, ask yourself if you could rename some things or create variables to improve readability. If that's not possible, write the comment in a way that both your colleagues and you will understand in 6 months.
Before writing a comment, ask yourself if you could rename some things or create variables to improve readability. If that's not possible, write the comment in a way that both your colleagues and you will understand in 6 months.
Context matters.
Above I said that moving business logic to action/service classes is good. But context matters
Here's code design advice from a popular "Laravel best practices" repo. There's absolutely no reason to put a 3-line check into a class. That's just overengineered
Above I said that moving business logic to action/service classes is good. But context matters
Here's code design advice from a popular "Laravel best practices" repo. There's absolutely no reason to put a 3-line check into a class. That's just overengineered
Use only what helps you and ignore everything else.
*Your goal to write more readable code.*
Your goal is NOT to do what someone said on the internet
These tips are just tactics that tend to help with clean code. Keep your end goal in mind and ask yourself "is this better?"
*Your goal to write more readable code.*
Your goal is NOT to do what someone said on the internet
These tips are just tactics that tend to help with clean code. Keep your end goal in mind and ask yourself "is this better?"