3.best PractiseGitHub - Alexeymezenin - Laravel-Best-Practices - Laravel Best Practices
3.best PractiseGitHub - Alexeymezenin - Laravel-Best-Practices - Laravel Best Practices
Star Notifications
Code Issues 26
README
You might also want to check out the real-world Laravel example application and Eloquent SQL reference
Translations:
Nederlands (by Protoqol)
Русский
Contents
Validation
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
Store dates in the standard format. Use accessors and mutators to modify date format
Bad:
$this->event->updateGeneralEvent($request->validated());
return back();
}
Good:
$this->event->updateGeneralEvent($request->validated());
return back();
}
🔝 Back to contents
Methods should do just one thing
A function should do just one thing and do it well.
Bad:
Good:
public function getFullNameAttribute(): string
{
return $this->isVerifiedClient() ? $this->getFullNameLong() : $this->getFullNameShort();
}
🔝 Back to contents
Fat models, skinny controllers
Put all DB related logic into Eloquent models.
Bad:
Good:
🔝 Back to contents
Validation
Move validation from controllers to Request classes.
Bad:
Good:
🔝 Back to contents
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:
...
}
class ArticleService
{
public function handleUploadedImage($image): void
{
if (!is_null($image)) {
$image->move(public_path('images') . 'temp');
}
}
}
🔝 Back to contents
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:
🔝 Back to contents
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. You
may want to check out Eloquent to SQL reference
Bad:
SELECT *
FROM `articles`
WHERE EXISTS (SELECT *
FROM `users`
WHERE `articles`.`user_id` = `users`.`id`
AND EXISTS (SELECT *
FROM `profiles`
WHERE `profiles`.`user_id` = `users`.`id`)
AND `users`.`deleted_at` IS NULL)
AND `verified` = '1'
AND `active` = '1'
ORDER BY `created_at` DESC
Good:
Article::has('user.profile')->verified()->latest()->get();
🔝 Back to contents
Mass assignment
Bad:
Good:
$category->article()->create($request->validated());
🔝 Back to contents
Do not execute queries in Blade templates and use eager loading (N + 1 problem)
Bad (for 100 users, 101 DB queries will be executed):
$users = User::with('profile')->get();
🔝 Back to contents
Chunk data for data-heavy tasks
Bad:
$users = $this->get();
Good:
🔝 Back to contents
Prefer descriptive method and variable names over comments
Bad:
Good:
if ($this->hasJoins())
🔝 Back to contents
Do not put JS and CSS in Blade templates and do not put any HTML in PHP classes
Bad:
Better:
Or
<button class="js-fav-article" data-article='@json($article)'>{{ $article->name }}<button>
In a Javascript file:
The best way is to use specialized PHP to JS package to transfer the data.
🔝 Back to contents
Use config and language files, constants instead of text in the code
Bad:
Good:
🔝 Back to contents
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.
Compiling assets Laravel Mix, Vite Grunt, Gulp, 3rd party packages
API authentication Laravel Passport, Laravel Sanctum 3rd party JWT and OAuth 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 Standard tools 3rd party tools
Task scheduling Laravel Task Scheduler Scripts and 3rd party packages
🔝 Back to contents
Follow Laravel naming conventions
Follow PSR standards.
hasOne or
belongsTo singular articleComment articleComments, article_comment
relationship
All other
plural articleComments articleComment, article_comments
relationships
snake_case without
Table column meta_title MetaTitle; article_meta_title
model name
Method in resource
table store saveArticle
controller
showFiltered.blade.php,
View kebab-case show-filtered.blade.php
show_filtered.blade.php
googleCalendar.php, google-
Config snake_case google_calendar.php
calendar.php
UpdateUserFormRequest,
FormRequest singular UpdateUserRequest
UserFormRequest, UserRequest
🔝 Back to contents
Convention over configuration
As long as you follow certain conventions, you do not need to add additional configuration.
Bad:
Good:
🔝 Back to contents
Use shorter and more readable syntax where possible
Bad:
$request->session()->get('cart');
$request->input('name');
Good:
session('cart');
$request->name;
More examples:
Session::get('cart') session('cart')
$request->session()->get('cart') session('cart')
App::make('Class') app('Class')
->first()->name ->value('name')
🔝 Back to contents
Use IoC / Service container instead of new Class
new Class syntax creates tight coupling between classes and complicates testing. Use IoC container or facades instead.
Bad:
Good:
...
$this->user->create($request->validated());
🔝 Back to contents
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:
$apiKey = env('API_KEY');
Good:
// config/api.php
'key' => env('API_KEY'),
🔝 Back to contents
Store dates in the standard format. Use accessors and mutators to modify date format
A date as a string is less reliable than an object instance, e.g. a Carbon-instance. It's recommended to pass Carbon objects between classes
instead of date strings. Rendering should be done in the display layer (templates):
Bad:
Good:
// Model
protected $casts = [
'ordered_at' => 'datetime',
];
// Blade view
{{ $object->ordered_at->toDateString() }}
{{ $object->ordered_at->format('m-d') }}
🔝 Back to contents
Do not use DocBlocks
DocBlocks reduce readability. Use a descriptive method name and modern PHP features like return type hints instead.
Bad:
/**
* The function checks if given string is a valid ASCII string
*
* @param string $string String we get from frontend which might contain
* illegal characters. Returns True is the string
* is valid.
*
* @return bool
* @author John Smith
*
* @license GPL
*/
Good:
🔝 Back to contents
Other good practices
Avoid using patterns and tools that are alien to Laravel and similar frameworks (i.e. RoR, Django). If you like Symfony (or Spring) approach for
building apps, it's a good idea to use these frameworks instead.
Releases
No releases published
Packages
No packages published
Contributors 67
+ 53 contributors