In this episode, we dive into the new incrementOrCreate
method that's been added to Eloquent in Laravel. If you've used methods like firstOrCreate
or firstOrNew
before, you'll know how handy they are for keeping your code clean and avoiding extra checks and logic. Well, incrementOrCreate
is here to solve a similar problem, but specifically for scenarios where you want to count things — like page visits, likes, or any other numerical activity — without duplicating records for the same unique attribute.
We start by looking at a classic use case: counting website visits by IP address. Traditionally, you'd try to firstOrCreate
a record based on the IP and then increment a counter if the record already exists. This usually involves fetching the record, checking if it was just created, and then possibly incrementing the counter yourself. It's not too hard, but it's more code than you might like.
That's where incrementOrCreate
really shines. With this new method, you can simply pass in the unique attributes (like IP address) and the column you want to increment, all in one go. If the record doesn't exist, it's created with an initial value; if it does exist, the counter just gets incremented. Super clean, super simple!
We also take a peek under the hood to see how incrementOrCreate
works — spoiler: it's basically a shortcut for firstOrCreate
followed by an increment, but all bundled together for you. Plus, you can customize things like the default value when creating, how much to increment by, and throw in other fields if you need.
By the end of this episode, you'll be ready to swap out your old logic and use incrementOrCreate
wherever you need to track and update counters in your Laravel apps. It's a small addition but a really awesome time-saver.