#005: Laravel’de Koşullu Sorgular İçin `when()` Metodunu Kullanın!


Eloquent sorgularında birden çok if
bloğu ile şartları kontrol etmek, kodunuzu hem uzatır hem de bakım maliyetini artırır. when()
metodu sayesinde sorgularınızı zincirleyerek hem daha temiz hem de esnek bir yapı elde edebilirsiniz... İşte örnek:
❌ Kötü Kullanım:
// Path: app/Http/Controllers/Api/V1/PostController.php
public function index(Request $request)
{
$query = Post::query();
if ($request->has('status')) {
$query->where('status', $request->status);
}
if ($request->has('category_id')) {
$query->where('category_id', $request->category_id);
}
if ($request->has('published_after')) {
$query->where('published_at', '>', $request->published_after);
}
return $query->get();
}
✅ Temiz, Okunabilir ve Sürdürülebilir Kod:
// Path: app/Http/Controllers/Api/V1/PostController.php
public function index(Request $request)
{
return Post::query()
->when($request->status, fn($q, $status) => $q->where('status', $status))
->when($request->category_id, fn($q, $category) => $q->where('category_id', $category))
->when($request->published_after, fn($q, $date) => $q->where('published_at', '>', $date))
->get();
}
Bu sayede;
- Sorgu zinciri kesintisiz ve akıcı kalır,
- Koşullar parametre olarak geçildiğinde otomatik uygulanır,
- Kod tekrarı ve fazladan
if
bloklarından kurtulursunuz.
when() hakkında daha fazla bilgi için resmi dokümana bkz: https://laravel.com/docs/queries#conditional-clauses
Peki siz projelerinizde when() metodunu kullanıyor musunuz? Veya kullanıyorsanız da nasıl kullanıyorsunuz? Yorumlarda deneyimlerinizi paylaşın, hep birlikte öğrenelim!
Daha fazla bu tarzda bilgi için takipte kalabilirsiniz:
- DailyDev: icin.tr/dailydev
- LinkedIn: icin.tr/linkedin
- Portföy: icin.tr/portfolio
- CV: icin.tr/cv
- Tüm Bağlantılar: icin.tr/me
Subscribe to my newsletter
Read articles from Erhan ÜRGÜN directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Erhan ÜRGÜN
Erhan ÜRGÜN
Laravel | AdonisJS | Back-End Developer