125 lines
4.3 KiB
Markdown
125 lines
4.3 KiB
Markdown
# Conventions & Style
|
||
|
||
## Follow Laravel Naming Conventions
|
||
|
||
| What | Convention | Good | Bad |
|
||
|------|-----------|------|-----|
|
||
| Controller | singular | `ArticleController` | `ArticlesController` |
|
||
| Model | singular | `User` | `Users` |
|
||
| Table | plural, snake_case | `article_comments` | `articleComments` |
|
||
| Pivot table | singular alphabetical | `article_user` | `user_article` |
|
||
| Column | snake_case, no model name | `meta_title` | `article_meta_title` |
|
||
| Foreign key | singular model + `_id` | `article_id` | `articles_id` |
|
||
| Route | plural | `articles/1` | `article/1` |
|
||
| Route name | snake_case with dots | `users.show_active` | `users.show-active` |
|
||
| Method | camelCase | `getAll` | `get_all` |
|
||
| Variable | camelCase | `$articlesWithAuthor` | `$articles_with_author` |
|
||
| Collection | descriptive, plural | `$activeUsers` | `$data` |
|
||
| Object | descriptive, singular | `$activeUser` | `$users` |
|
||
| View | kebab-case | `show-filtered.blade.php` | `showFiltered.blade.php` |
|
||
| Config | snake_case | `google_calendar.php` | `googleCalendar.php` |
|
||
| Enum | singular | `UserType` | `UserTypes` |
|
||
|
||
## Prefer Shorter Readable Syntax
|
||
|
||
| Verbose | Shorter |
|
||
|---------|---------|
|
||
| `Session::get('cart')` | `session('cart')` |
|
||
| `$request->session()->get('cart')` | `session('cart')` |
|
||
| `$request->input('name')` | `$request->name` |
|
||
| `return Redirect::back()` | `return back()` |
|
||
| `Carbon::now()` | `now()` |
|
||
| `App::make('Class')` | `app('Class')` |
|
||
| `->where('column', '=', 1)` | `->where('column', 1)` |
|
||
| `->orderBy('created_at', 'desc')` | `->latest()` |
|
||
| `->orderBy('created_at', 'asc')` | `->oldest()` |
|
||
| `->first()->name` | `->value('name')` |
|
||
|
||
## Use Laravel String & Array Helpers
|
||
|
||
Laravel provides `Str`, `Arr`, `Number`, and `Uri` helper classes that are more readable, chainable, and UTF-8 safe than raw PHP functions. Always prefer them.
|
||
|
||
Strings — use `Str` and fluent `Str::of()` over raw PHP:
|
||
```php
|
||
// Incorrect
|
||
$slug = strtolower(str_replace(' ', '-', $title));
|
||
$short = substr($text, 0, 100) . '...';
|
||
$class = substr(strrchr('App\Models |