Back to Presentations
laravel logo

How to Write Clean Code in Laravel

Host: Mohammad Rahmani

Date: July 4, 2021

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”

Martin Fowler
Software Developer
(martinfowler.com)

DOS & DON'TS

Controller name SHOULD start with a noun (in singular form) followed by the word “Controller”.

controller
model

Model names SHOULD be in singular form with its first letter in uppercase

Migration filenames SHOULD follow to following pattern

migration
migration

Model properties SHOULD be in snake_case

Table column names SHOULD be in snake_case without the model name

migration
migration

hasOne or belongsTo relationship methods MUST be in singular form

You SHOULD Use Resource Controllers unless you have any particular reason not to do so

migration
migration

Methods should be in camelCase

Routes should be in plural form of the resource it is trying to manipulate and SHOULD be all lower-case

migration
migration

FormRequests have been around since Laravel 5.0 so Move validation from controllers to Request classes.

Let the code speak for itself. Your controllers will become bloated every time you validate. Write scalable code through dependency injection.

migration
migration

When injecting a model ID to a route or controller action, you will often query to retrieve the model that corresponds to that ID. Laravel’s route model binding provides a convenient way to automatically inject the model instances directly into your routes.

Single responsibility principle, A class and a method should have only one responsibility.

migration
migration

A Good Example: 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.

migration
migration

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.

Eloquent allows you to write readable and maintainable code. Also, Eloquent has great built-in tools like soft deletes, events, scopes etc.

migration
migration

Use config and language files, constants instead of text in the code

Store dates in the standard format. Use accessors and mutators to modify date format

migration
migration

Use Mass assignment in one line instead of too many lines and assign data to each field

Other good practices

Never put any logic in routes files.

Minimize usage of vanilla PHP in Blade templates.

Host: Mohammad Rahmani

Date: July 4, 2021