Laravel's incrementOrCreate Method

February 5th, 2025 • 2 minutes read time

Added in Laravel 11, incrementOrCreate is a method to create a record uniquely based on a pre-defined array.

Once that record exists, a chosen column will get incremented each time incrementOrCreate is called. As we'll explore in this article, this saves on writing a lot of our own logic.

Throughout the article, we'll use a Visit model as an example — where we want to increment the Visit count column based on unique user information, like an IP address.

Here's how we'd insert a Visit record and then increment count only once the record is already created:

$visit = Visit::firstOrCreate([
    'ip_address' => request()->ip()
], [
    'count' => 1
]);

if (!$visit->wasRecentlyCreated) {
    $visit->increment('count');
}

With this code, we use firstOrCreate to only create the record if the ip_address doesn't already exist. If it does, firstOrCreate returns the Visit instance.

We then use wasRecentlyCreated to see if the record existed before, and if so, increment the count column.

Pretty annoying to have to write all this, so let's look at the new incrementOrCreate method!

To increment a column for an existing record or initially create a record in Laravel, we can now use incrementOrCreate.

Here's what the above example can be transformed into now:

Visit::incrementOrCreate([
    'ip_address' => request()->ip(),
], 'count');

A nice, clean way to increment the count column for an existing record where the ip_address matches.

You can also pass in additional arguments to incrementOrCreate to customise how it works. For example, you're able to choose the initial value inserted and the step for the increment:

Visit::incrementOrCreate([
    'ip_address' => request()->ip(),
], 'count', 10, 100);

In this example, it would insert 10 to begin with and then increment by 100 every time this runs.

So, a super helpful shortcut for incrementing or creating a record in Laravel. It makes sense, considering we already have methods like firstOrCreate, firstOrNew, etc.

If you found this article helpful, you'll love our practical screencasts.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first!