✅ 要点サマリ
- Laravel の Query Builder は “SQL を PHP で安全に書くラッパ”
- 基本形は
DB::table('テーブル') - SELECT / WHERE / INSERT / UPDATE / DELETE はそれぞれメソッドで書ける
-
where()/whereIn()/first()/pluck()が特に重要
✅ ステップバイステップ:基礎クエリ(超基本)
① *全件取得(SELECT )
DB::table('users')->get();
② 1件だけ取得(LIMIT 1)
DB::table('users')->first();
③ 特定の条件で取得(WHERE)
DB::table('users')
->where('email', 'test@example.com')
->first();
④ 複数条件(AND)
DB::table('users')
->where('status', 1)
->where('age', '>=', 20)
->get();
⑤ IN 句(whereIn)
スキル名から id を取るとき超便利。
DB::table('skills')
->whereIn('name', ['PHP', 'Laravel'])
->pluck('id');
→ 結果例:[1, 3]
⑥ 特定カラムだけ取得(pluck)
DB::table('users')->pluck('email');
→ ['a@example.com', 'b@example.com', ...]
🌟 よく使うパターン:id の取得
▶︎ 1件の id を取る
$id = DB::table('skills')
->where('name', 'PHP')
->value('id');
▶︎ 複数の id を取得(whereIn + pluck)
$ids = DB::table('skills')
->whereIn('name', $skillNames) // ['PHP', 'React', ...]
->pluck('id'); // [1,5,11,...]
🌟 INSERT(データ登録)
① 1件の Insert
DB::table('projects')->insert([
'title' => '新しい案件',
'description' => '説明文',
'created_at' => now(),
'updated_at' => now(),
]);
② insertGetId(作成したレコードの id を取得)
$projectId = DB::table('projects')->insertGetId([
'title' => '新しい案件',
'created_at' => now(),
'updated_at' => now(),
]);
🌟 UPDATE(データ更新)
DB::table('projects')
->where('id', $projectId)
->update([
'title' => 'タイトル更新',
'updated_at' => now(),
]);
🌟 DELETE(削除)
DB::table('projects')
->where('id', $id)
->delete();
🌟 ORDER / LIMIT など
ORDER BY
DB::table('users')->orderBy('created_at', 'desc')->get();
LIMIT
DB::table('users')->limit(10)->get();
🎯 設計の意図 & 注意点
- Query Builder は SQL を直接書かず、安全に DB を操作できる
- where や pluck などは Eloquent とほぼ同じ
- Repository 層では Query Builder を使うと柔軟で安全
- SQL インジェクション対策が自動で効くので安心