
-
By Andrés Pinto
-
Apr 21, 2025
- Laravel
- Featured
-
2 min read
5 Hidden Laravel Features That Will Instantly Clean Up Your Code
if (request('category')) { $query->where('category_id', request('category')); }
$products = $query->get();With when():$products = Product::query() ->when(request('category'), function ($q, $category) { $q->where('category_id', $category); }) ->get();It’s readable, concise, and scales better when you have multiple conditional filters.3. Sort Collections Using sortByDesc()If you’ve already fetched a collection and need to sort it in descending order by a specific key, don’t requery — just sort it with sortByDesc().Example:$products = Product::all();
// Sort by highest sales $topSelling = $products->sortByDesc('sold_count');Quick and efficient — no need to hit the database again.4. Use isEmpty() Instead of count() === 0Checking for empty collections with count() works, but Laravel collections offer a more expressive and readable way: isEmpty().Instead of this:if ($orders->count() === 0) { echo "No orders yet."; }Do this:if ($orders->isEmpty()) { echo "No orders yet."; }Small change, big readability boost.5. Filter Relationships with whereRelation() (Laravel 9+)Filtering data based on related models used to require whereHas() with a closure. Since Laravel 9, there’s a simpler alternative: whereRelation().Old way:$orders = Order::whereHas('customer', function ($q) { $q->where('city', 'Jakarta'); })->get();New and cleaner:$orders = Order::whereRelation('customer', 'city', 'Jakarta')->get();Less boilerplate, and the intent is crystal clear.Final ThoughtsLaravel’s hidden gems like @forelse, when(), sortByDesc(), isEmpty(), and whereRelation() can take your code from "it works" to "this is clean." They're not just sugar syntax — they help you write more expressive and readable code that other developers (including future you) will appreciate.If you found this helpful, consider bookmarking it or sharing it with your team. And if you have your own favorite underused Laravel tips, drop them in the comments!