Customizing additional parameters in FirstOrCreate in Laravel 5.3

Posted on June 29, 2016

Warning: This post is over a year old. I don't always update old posts with new information, so some of this information may be out of date.

More Laravel 5.3 goodies! This time, it's an update to the Eloquent firstOrCreate method.

If you've never used it before, you can pass an array of values to firstOrCreate and it will look up whether a record exists with those properties. If so, it'll return that instance; if not, it'll create it and then return the created instance.

Here's an example:

$tag = Tag::firstOrCreate(['slug' => 'matts-favorites']);

This is good. It's very useful. But.

What if the tag with the slug matts-favorites represents a tag with the label Matts favorites?

$tag = Tag::firstOrCreate(['slug' => 'matts-favorites', 'label' => 'Matts Favorites']);

OK, that worked well. But now, imagine this scenario: you want to create a tag with slug of matts-favorites and label of Matt's favorites unless there's already a tag with slug matts-favorites, in which case you just want that tag—even if it doesn't give you the label you want? Check it:

$tag = Tag::firstOrCreate(
    ['slug' => 'matts-favorites'],
    ['label' => "Matt's Favorites"]

We've specified that the Tag model should look up a tag where slug is matts-favorites and return it if so. And if not, create a new tag with slug matts-favorites and label Matt's Favorites, and return that. Bam. Beautiful.

Comments? I'm @stauffermatt on Twitter

Tags: laravel  •  laravel 5.3  •  eloquent