One Laravel feature that quietly improves both performance and code clarity: keyBy().
By default, Eloquent returns collections indexed numerically. That’s fine—until you need fast lookups inside loops. This is where it keyBy() changes the game.
keyBy() lets you re-index a collection using:
• a single column (staff_id)
• or a custom/composite key (like staff_id + date)
Once keyed, you can instantly fetch records with $collection->get($key) instead of looping or querying again.
Why it matters:
✔ fewer database hits
✔ faster execution
✔ cleaner, more readable logic
✔ easier to scale
It’s a small method, but in real-world Laravel projects, it makes a big difference.