Hello everyone. In this post, I will talk about the Laravel Best Practices for Developers. These are common usage ways for developers to understand each other projects for support and this makes it easy for you to maintain your project.
Single responsibility principle
A class and a method should have only one responsibility.
Fat models, skinny controllers
Put all DB related logic into Eloquent models or into Repository classes if you’re using Query Builder or raw SQL queries.
Move validation from controllers to Request classes.
Business logic should be in service class
A controller must have only one responsibility, so move business logic from controllers to service classes.
Don’t repeat yourself (DRY)
Reuse code when you can. SRP is helping you to avoid duplication. Also, reuse Blade templates, use Eloquent scopes etc.
Prefer to use Eloquent over using Query Builder and raw SQL queries. Prefer collections over arrays
Eloquent allows you to write readable and maintainable code. Also, Eloquent has great built-in tools like soft deletes, events, scopes etc.
Do not execute queries in Blade templates and use eager loading (N + 1 problem)
Bad (for 100 users, 101 DB queries will be executed):
Good (for 100 users, 2 DB queries will be executed):
Comment your code, but prefer descriptive method and variable names over comments
Do not put JS and CSS in Blade templates and do not put any HTML in PHP classes
Use config and language files, constants instead of text in the code
Use standard Laravel tools accepted by community
Prefer to use built-in Laravel functionality and community packages instead of using 3rd party packages and tools. Any developer who will work with your app in the future will need to learn new tools. Also, chances to get help from the Laravel community are significantly lower when you’re using a 3rd party package or tool. Do not make your client pay for that.
Follow Laravel naming conventions
Follow PSR standards.
Also, follow naming conventions accepted by Laravel community:
Use shorter and more readable syntax where possible
Use IoC container or facades instead of new Class
new Class syntax creates tight coupling between classes and complicates testing. Use IoC container or facades instead.
Do not get data from the
.env file directly
Pass the data to config files instead and then use the
config() helper function to use the data in an application.
Store dates in the standard format. Use accessors and mutators to modify date format
Other good practices
Never put any logic in route files.
Minimize usage of vanilla PHP in Blade templates.
If you like this article please follow me for new useful information :))
You can find the source of this article on their Link
Also, check my other post from here.