Skip to content

Commit cf830bb

Browse files
committed
Add DB table rule.
1 parent 1ba108a commit cf830bb

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

.ai/laravel/skill/laravel-best-practices/SKILL.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ Check sibling files, related controllers, models, or tests for established patte
6767
- Attribute casts in the `casts()` method
6868
- Cast date columns, use Carbon instances in templates
6969
- `whereBelongsTo($model)` for cleaner queries
70+
- Never hardcode table names — use `(new Model)->getTable()` or Eloquent queries
7071

7172
### 6. Validation & Forms → `rules/validation.md`
7273

.ai/laravel/skill/laravel-best-practices/rules/eloquent.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,3 +120,29 @@ Correct:
120120
Post::whereBelongsTo($user)->get();
121121
Post::whereBelongsTo($user, 'author')->get();
122122
```
123+
124+
## Avoid Hardcoded Table Names in Queries
125+
126+
Never use string literals for table names in raw queries, joins, or subqueries. Hardcoded table names make it impossible to find all places a model is used and break refactoring (e.g., renaming a table requires hunting through every raw string).
127+
128+
Incorrect:
129+
```php
130+
DB::table('users')->where('active', true)->get();
131+
132+
$query->join('companies', 'companies.id', '=', 'users.company_id');
133+
134+
DB::select('SELECT * FROM orders WHERE status = ?', ['pending']);
135+
```
136+
137+
Correct — reference the model's table:
138+
```php
139+
DB::table((new User)->getTable())->where('active', true)->get();
140+
141+
// Even better — use Eloquent or the query builder instead of raw SQL
142+
User::where('active', true)->get();
143+
Order::where('status', 'pending')->get();
144+
```
145+
146+
Prefer Eloquent queries and relationships over `DB::table()` whenever possible — they already reference the model's table. When `DB::table()` or raw joins are unavoidable, always use `(new Model)->getTable()` to keep the reference traceable.
147+
148+
**Exception — migrations:** In migrations, hardcoded table names via `DB::table('settings')` are acceptable and preferred. Models change over time but migrations are frozen snapshots — referencing a model that is later renamed or deleted would break the migration.

0 commit comments

Comments
 (0)