Its not a Laravel adaptation of SOLID principles, patterns etc. Here you’ll find the best practices which are usually ignored in real life Laravel projects.
Table of Contents
- Follow Laravel naming conventions
- Use shorter and more readable syntax where possible
- Single responsibility principle
- Fat models, skinny controllers
- Validation
- Business logic should be in service class
- Don’t repeat yourself (DRY)
- Prefer to use Eloquent over using Query Builder and raw SQL queries. Prefer collections over arrays
- Mass assignment
- Do not execute queries in Blade templates and use eager loading (N + 1 problem)
- 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
- Use IoC container or facades instead of new Class
- Do not get data from the “.env”-file directly
- Store dates in the standard format. Use accessors and mutators to modify date format
- Other good practices
Follow Laravel naming conventions
Follow PSR standards.
Also, follow naming conventions accepted by Laravel community:
What | How | Good | Bad |
---|---|---|---|
Controller | singular | ArticleController | |
Route | plural | articles/1 | |
Named route | snake_case with dot notation | users.show_active | |
Model | singular | User | |
hasOne or belongsTo relationship | singular | articleComment | |
All other relationships | plural | articleComments | |
Table | plural | article_comments | |
Pivot table | singular model names in alphabetical order | article_user | |
Table column | snake_case without model name | meta_title | |
Foreign key | singular model name with _id suffix | article_id | |
Primary key | – | id | |
Migration | – | 2017_01_01_000000_create_articles_table | |
Method | camelCase | getAll | |
Function | snake_case | abort_if | |
Method in resource controller | more infos: table | store | |
Method in test class | camelCase | testGuestCannotSeeArticle | |
Model property | snake_case | $model->model_property | |
Variable | camelCase | $anyOtherVariable | |
Collection | descriptive, plural | $activeUsers = User::active()->get() | |
Object | descriptive, singular | $activeUser = User::active()->first() | |
Config and language files index | snake_case | articles_enabled | |
View | kebab-case | show-filtered.blade.php | |
Config | kebab-case | google-calendar.php | |
Contract (interface) | adjective or noun | Authenticatable | |
Trait | adjective | Notifiable |
Use shorter and more readable syntax where possible
Bad:
Good:
More examples:
Common syntax | Shorter and more readable syntax |
---|---|
Session::get('cart') | session('cart') |
$request->session()->get('cart') | session('cart') |
Session::put('cart', $data) | session(['cart' => $data]) |
$request->input('name'), Request::get('name') | $request->name, request('name') |
return Redirect::back() | return back() |
is_null($object->relation) ? $object->relation->id :
null
} | optional($object->relation)->id |
return view('index')->with('title', $title)->with('client',
$client) | return view('index', compact('title', 'client')) |
$request->has('value') ? $request->value :
'default'; | $request->get('value', 'default') |
Carbon::now(), Carbon::today() | now(), today() |
App::make('Class') | app('Class') |
->where('column', '=', 1) | ->where('column', 1) |
->orderBy('created_at', 'desc') | ->latest() |
->orderBy('age', 'desc') | ->latest('age') |
->orderBy('created_at', 'asc') | ->oldest() |
->select('id', 'name')->get() | ->get(['id', 'name']) |
->first()->name | ->value('name') |
Single responsibility principle
A class and a method should have only one responsibility.
Bad:
Good:
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.
Bad:
Good:
Validation
Move validation from controllers to Request classes.
Bad:
Good:
Business logic should be in service class
A controller must have only one responsibility, so move business logic from controllers to service classes.
Bad:
Good:
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.
Bad:
Good:
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.
Bad:
Good:
Mass assignment
Bad:
Good:
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
Bad:
Better:
Good:
Do not put JS and CSS in Blade templates and do not put any HTML in PHP classes
Bad:
Better:
In a Javascript file:
The best way is to use specialized PHP to JS package to transfer the data.
Use config and language files, constants instead of text in the code
Bad:
Good:
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.
Task | Standard tools | 3rd party tools |
---|---|---|
Authorization | Policies | Entrust, Sentinel and other packages |
Compiling assets | Laravel Mix | Grunt, Gulp, 3rd party packages |
Development Environment | Homestead | Docker |
Deployment | Laravel Forge | Deployer and other solutions |
Unit testing | PHPUnit, Mockery | Phpspec |
Browser testing | Laravel Dusk | Codeception |
DB | Eloquent | SQL, Doctrine |
Templates | Blade | Twig |
Working with data | Laravel collections | Arrays |
Form validation | Request classes | 3rd party packages, validation in controller |
Authentication | Built-in | 3rd party packages, your own solution |
API authentication | Laravel Passport | 3rd party JWT and OAuth packages |
Creating API | Built-in | Dingo API and similar packages |
Working with DB structure | Migrations | Working with DB structure directly |
Localization | Built-in | 3rd party packages |
Realtime user interfaces | Laravel Echo, Pusher | 3rd party packages and working with WebSockets directly |
Generating testing data | Seeder classes, Model Factories, Faker | Creating testing data manually |
Task scheduling | Laravel Task Scheduler | Scripts and 3rd party packages |
DB | MySQL, PostgreSQL, SQLite, SQL Server | MongoDB |
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.
Bad:
Good:
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.
Bad:
Good:
Store dates in the standard format. Use accessors and mutators to modify date format
Bad:
Good:
Other good practices
Never put any logic in routes files.
Minimize usage of vanilla PHP in Blade templates.
Thanks to for inspiration…
@alexeymezenin (laravel-best-practices)