More 5.3 goodies! This time, it’s an update to the Eloquent 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.

Source link


Please enter your comment!
Please enter your name here