Coding Guidelines
About Laravel
First and foremost, Laravel provides the most value when you write things the way Laravel intended you to write. If there's a documented way to achieve something, follow it. Whenever you do something differently, make sure you have a justification for why you didn't follow the defaults.
General PHP Rules
Code style must follow PSR-1, PSR-2 and PSR-12. Generally speaking, everything string-like that's not public-facing should use camelCase. Detailed examples on these are spread throughout the guide in their relevant sections.
Class defaults
By default, we don't use final. In our team, there aren't many benefits that final offers as we don't rely too much on inheritance. For our open source stuff, we assume that all our users know they are responsible for writing tests for any overwritten behaviour.
Nullable and union types
Whenever possible use the short nullable notation of a type, instead of using a union of the type with null.
public ?string $variable;public string | null $variable;Void return types
If a method returns nothing, it should be indicated with void. This makes it more clear to the users of your code what your intention was when writing it.
// in a Laravel model
public function scopeArchived(Builder $query): void
{
$query->
...
}Typed properties
You should type a property whenever possible. Don't use a docblock.
Enums
Values in enums should use PascalCase.
Docblocks
Don't use docblocks for methods that can be fully type hinted (unless you need a description).
Only add a description when it provides more context than the method signature itself. Use full sentences for descriptions, including a period at the end.
Always import the classnames in docblocks.
Using multiple lines for a docblock, might draw too much attention to it. When possible, docblocks should be written on one line.
If a variable has multiple types, the most common occurring type should be first.
If a function requires a docblock for a single parameter or return type, add all other docblocks as well.
Docblocks for iterables
When your function gets passed an iterable, you should add a docblock to specify the type of key and value. This will greatly help static analysis tools understand the code, and IDEs to provide autocompletion.
In this example, typedArgument needs a docblock too:
The keys and values of iterables that get returned should always be typed.
If your array or collection has a few fixed keys, you can typehint them too using {} notation.
If there is only one docblock needed, you may use the short version.
Constructor property promotion
Use constructor property promotion if all properties can be promoted. To make it readable, put each one on a line of its own. Use a comma after the last one.
Traits
Each applied trait should go on its own line, and the use keyword should be used for each of them. This will result in clean diffs when traits are added or removed.
Strings
When possible prefer string interpolation above sprintf and the . operator.
Ternary operators
Every portion of a ternary expression should be on its own line unless it's a really short expression.
If statements
Bracket position
Always use curly brackets.
Happy path
Generally a function should have its unhappy path first and its happy path last.
Avoid else
In general, else should be avoided because it makes code less readable. In most cases it can be refactored using early returns. This will also cause the happy path to go last, which is desirable.
Another option to refactor an else away is using a ternary
Compound ifs
In general, separate if statements should be preferred over a compound condition. This makes debugging code easier.
Comments
Comments should be avoided as much as possible by writing expressive code. If you do need to use a comment, format it like this:
A possible strategy to refactor away a comment is to create a function with name that describes the comment
Whitespace
Statements should be allowed to breathe. In general always add blank lines between statements, unless they're a sequence of single-line equivalent operations. This isn't something enforceable, it's a matter of what looks best in its context.
Don't add any extra empty lines between {} brackets.
Configuration
Configuration files must use kebab-case.
Configuration keys must use snake_case.
Avoid using the env helper outside of configuration files. Create a configuration value from the env variable like above. Read more about why it's important to only use the env helper in configuration files in the Laravel documentation.
When adding config values for a specific service, add them to the services config file. Do not create a new config file.
Artisan commands
The names given to artisan commands should all be kebab-cased.
A command should always give some feedback on what the result is. Minimally you should let the handle method spit out a comment at the end indicating that all went well.
When the main function of a result is processing items, consider adding output inside of the loop, so progress can be tracked. Put the output before the actual process. If something goes wrong, this makes it easy to know which item caused the error.
At the end of the command, provide a summary on how much processing was done.
Routing
Public-facing urls must use kebab-case.
Prefer to use the route tuple notation when possible.
Route names must use camelCase.
All routes have an HTTP verb, that's why we like to put the verb first when defining a route. It makes a group of routes very readable. Any other route options should come after it.
Route parameters should use camelCase.
A route url should not start with / unless the url would be an empty string.
Controllers
Controllers that control a resource must use the plural resource name.
Try to keep controllers simple and stick to the default CRUD keywords (index, create, store, show, edit, update, destroy). Extract a new controller if you need other actions.
In the following example, we could have PostsController@favorite, and PostsController@unfavorite, or we could extract it to a separate FavoritePostsController.
Here we fall back to default CRUD words, store and destroy.
This is a loose guideline that doesn't need to be enforced.
Views
View files must use kebab-case.
Validation
When using multiple rules for one field in a form request, avoid using |, always use array notation. Using an array notation will make it easier to apply custom rule classes to a field.
All custom validation rules must use snake_case:
Blade Templates
Indent using four spaces.
Don't add spaces after control structures.
Authorization
Policies must use camelCase.
Try to name abilities using default CRUD words. One exception: replace show with view. A server shows a resource, a user views it.
Translations
Translations must be rendered with the __ function. We prefer using this over @lang in Blade views because __ can be used in both Blade views and regular PHP code. Here's an example:
Naming Classes
Naming things is often seen as one of the harder things in programming. That's why we've established some high level guidelines for naming classes.
Controllers
Generally controllers are named by the plural form of their corresponding resource and a Controller suffix. This is to avoid naming collisions with models that are often equally named.
e.g. UsersController or EventDaysController
When writing non-resourceful controllers you might come across invokable controllers that perform a single action. These can be named by the action they perform again suffixed by Controller.
e.g. PerformCleanupController
Resources (and transformers)
Both Eloquent resources and Fractal transformers are plural resources suffixed with Resource or Transformer accordingly. This is to avoid naming collisions with models.
Jobs
A job's name should describe its action.
E.g. CreateUser or PerformDatabaseCleanup
Events
Events will often be fired before or after the actual event. This should be very clear by the tense used in their name.
E.g. ApprovingLoan before the action is completed and LoanApproved after the action is completed.
Listeners
Listeners will perform an action based on an incoming event. Their name should reflect that action with a Listener suffix. This might seem strange at first but will avoid naming collisions with jobs.
E.g. SendInvitationMailListener
Commands
To avoid naming collisions we'll suffix commands with Command, so they are easiliy distinguisable from jobs.
e.g. PublishScheduledPostsCommand
Mailables
Again to avoid naming collisions we'll suffix mailables with Mail, as they're often used to convey an event, action or question.
e.g. AccountActivatedMail or NewEventMail
Enums
Enums don't need to be prefixed as in most cases, it is clear by reading the name that it is an enum.
e.g. OrderStatus or BookingType or Suit
Was this helpful?