In this episode, we dive into the world of custom Laravel collections and see how they can help clean up and simplify our code, especially when dealing with Eloquent models. We start by walking through a real example: handling user notifications. After setting up a fresh Laravel project, we create a Notification model, add a migration, and seed some notifications for a user. Traditionally, if you want to mark multiple notifications as read, you'd use a standard collection and loop through with each()
. Instead, we show how to create a NotificationCollection
with a custom method (markRead
), allowing you to batch update your notifications in a single, tidy method call. Much nicer!
Next, we look at another common scenario: storing and retrieving user settings (as key-value pairs) for each user. Rather than querying for a specific setting over and over with where
clauses, we build a SettingCollection
with some magic to let us access settings like $user->settings->player_speed
. To do this, we override Laravel's collection behavior, cleverly intercepting property access for a more intuitive (and shorter!) syntax when fetching setting values. We cover the gotchas too, like how the values you get are always strings and may need casting.
By the end of the video, you'll see two practical, real-world uses for custom collections in Laravel—making your code more expressive, maintainable, and fun to write!