Top
laravel best practices

Top 10 Laravel Best Practices You Should Follow

With the increasing use of smartphones, websites and apps will undoubtedly not reduce. So, it’s better to get used to new development frameworks. As new web app development languages are entering the market, the wise thing to do would be to adapt to it. The best framework would be Laravel. 

Laravel is developed for web artisans whose chaotic work needs a little calmness. Laravel framework is developed by Taylor Otwell in 2011. Being programmed to not just fasten your work but also organize them, Laravel comes with tools that are a self cleanser.

Laravel has rolled out various versions from laravel 5 to Laravel 5.8 (the recent one). The recent version i.e., Laravel 5.8 encompasses expressive syntax, amazing ORM, routing library and a brilliant tool that makes data migration easier between developers. In this article we have tried to curate the laravel best practices that we have learned in the last 7 years.

So, What Are The Laravel Best Practices We Follow At Innofied?

At Innofied, we always try to follow best practices to make sure that our codes are always clean so that we deliver amazing results for our clients.

1. Use The Latest Version 

When you are using the current stable version, you will be entitled to a secure and high-performance web solution. It is always advisable to work on the latest Laravel version. Presently 5.8 is the latest version that should be put to use when you are developing a web solution with Laravel.

2. Do Not Execute Queries In Blade Templates

Not to Do (for 100 posts, 101 DB queries will be executed):

@foreach (Post::all() as $post)

{{ $post->category->name }}

@endforeach

To Do (for 100 posts, 2 DB queries will be executed):

$posts = Post::with(‘category’)->get();

@foreach ($posts as $post)

{{ $post->category->name }}

@endforeach

3. Use Eloquent Orm 

Eloquent ORM is one of the most powerful features, which is used to extract data that will be shown to the end users through a single query. This is one of the best practice of developing in laravel would be to take care of the naming convention of your model. Eloquent ORM is also working for optimizing the queries part.

Not to Do:

SELECT *

FROM `posts`

WHERE EXISTS (SELECT *

FROM `users`

WHERE `posts`.`user_id` = `users`.`id`

AND EXISTS (SELECT *

FROM `profiles`

WHERE `profiles`.`user_id` = `users`.`id`)

AND `users`.`deleted_at` IS NULL)

AND `active` = ‘1’

ORDER BY `created_at` DESC

Should Use:

Post::has(‘user.profile’)->active()->latest()->get();

 

Related read: Top 10 Best Practices We Follow for React Native

4. Use Naming Conventions

https://www.innofied.com/how-much-does-an-app-cost/The recommended standards should be followed as per the experts are PSR-2 and PSR-4.

WhatHowShould FollowNot to Use
ControllersingularPostControllerPostsController
Routepluralposts/1post/1
Named routesnake_case with dot notationusers.show_activeusers.show-active, show-active-users
ModelsingularUserUsers
hasOne or belongsTo relationshipsingularpostCommentpostComments, post_comment
All other relationshipspluralpostCommentspostComment, post_comments
Tablepluralpost_commentspost_comment, postComments
Pivot tablesingular model names in alphabetical orderpost_useruser_post, posts_users
Model propertysnake_case$model->created_at$model->createdAt
Foreign keysingular model name with _id suffixpost_idPostId, id_post, posts_id
Primary keyidcustom_id
Migration2019_05_08_000000_create_posts_table2019_05_08_000000_posts
MethodcamelCasegetAllget_all
Method in resource controllertablestoresavePost
VariablecamelCase$postsWithAuthor$posts_with_creator

5. Artisan Command Line Interface 

Laravel has its own command line interface known as Artisan. It is recommended to make the best use of Artisan CLI as it positively influences the development process. It provides various helpful commands to speed up the application development process.

6. Use Of Autoload

In Laravel, any class or even plain PHP code can be used, as long as it could be auto-loaded. This improves the performance of the scripts by preventing PHP from checking if the file is already been loaded or not. PHP will let you know if it is needed when it is needed.

7. Using Migrations 

Making generous use of migrations is yet another important point that when considered will help the programmers in creating web solutions. Database migrations can be put to use for constructing a table, adding and altering the fields

8. Validation

Move validation from controllers to Request classes.

Not To Use:

public function store(Request $request)

{

$request->validate([

‘title’ => ‘required|unique:articles|max:255’,

‘body’ => ‘required’,

‘publish_at’ => ‘nullable|date’,

]);

}

Should Use:

public function store(ArticleRequest $request)

{

}

 

class ArticleRequest extends Request

{

public function rules()

{

return [

‘title’ => ‘required|unique:articles|max:255’,

‘body’ => ‘required’,

‘publish_at’ => ‘nullable|date’,

];

}

}

Related read: Top 10 Angular JS Best Practices

9. Compiling Assets :

Keeping all your assets in different files will indeed prove to be useful when you are in the development stage. Laravel Mix is in build package, which can be used to complite assets. Also there are various 3rd party packages are also available.

10. Removing Unnecessary Plugins :

If you find the existence of many unnecessary plugins, then it is high time to remove these plugins. Moreover, the unused plugins can be easily disabled by the developer without disturbing the rest of the functions.

Wrapping It Up

It’s been 7 years I have been developing web apps through Laravel and I swore I have not used any other framework. The constant changes and improvements provided has made the PHP development process seamless. Laravel provides you top-notch security so your product is shielded from threats like cross-site request forgery. Laravel works perfectly fine even in our small budget projects. So you do not have to worry about extravagant prices.

There are many advantages of Laravel that I can think of but not all can be written here. I can tell you following these best practices will produce a high-end final product. You do not have to worry about any new development framework, because Laravel is here for long.

Also, if you also happen to have some laravel practices that works great for you, tell us in the comments section below!

laravel best practices

Swarnendu De

Swarnendu is the Co-founder and Lead architect at Innofied. For the last seven years, he has been working with numerous JavaScript technologies including Backbone.js, Node.js, ExtJS, Sencha, and so on, and has developed more than 50 complex JavaScript-based applications thus far. He is the author of the book Backbone.js Patterns and Best Practices. Swarnendu regularly writes at his personal blog, Innofied Blog, the Tuts+ network, and provides support and assistance for JavaScript, Sencha and much more around the web. You can reach him through his website at http://www.swarnendude.com or via Twitter at @swarnendude