Best Practices in Laravel You Should Know

 

Nowadays, every web developer codes in their own style. It’s the same if we’re working using the Laravel framework where everything is in place but usually we misused the terminology here. It’s fine when it comes to different styles, but we must make sure that our codes follow the best practices. This means, our codes have to be reusable, scalable, maintainable, and testable.

Ok then, what makes our codes become a bad or good one? Well, because PHP is an OOP (Object Oriented Programming) language, then we should follow the OOP principle such as the SOLID principle  (We’ll discuss in detail about the SOLID Principles in the future) and consider using the OOP mechanism such as abstract, inheritance, classes/objects, constructor and etc.

In this article, I’ll show you some best practices in Laravel based on the OOP principles.

  • DRY ( Don’t Repeat Yourself )

Well, Reuse code as much as possible, and SRP can help you avoid duplicating wheels. In addition, try to reuse the Blade template and use Eloquent’s scopes method to implement the code.

Example:

Don’t Repeat Yourself

Best practices in Laravel:

Don’t Repeat Yourself

 

  • Don’t execute queries in Blade templates

Even though execute queries in the blade is possible, it’s not the best thing to do.

Bad way: It’ll cause N+1 trouble.

It’ll cause N+1 trouble.

Best practices in Laravel:

Good Practice:

 

  • Use DB Transaction

If we have some complicated and long queries, then we should consider using DB transactions. By using this feature, we can easily roll back the DB if needed to make sure that our data is not saved into DB, so we’re sure that our data are reliable.

Use DB Transaction

 

  • Fat Models, Skinny Controllers

If we have a pretty complicated query builder or raw SQL, we should move this query into Models or Repositories.

Fat Models, Skinny Controllers

 

  • Business Logic in Service Class

Related to the 1st point above where we should have a skinny controller, then we should move all the business logic in the separate service classes. So controllers should only have one responsibility, and hopefully, we can reuse this service in other controllers.

Business Logic in Service Class

 

  • Do Not Hardcode the Text

Do Not Hardcode the Text

 

Contact us on your Laravel project!

Recent Posts

logo