Series This post is in a series on New Features in Laravel 5.3.

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


This is part of a series of posts on New Features in Laravel 5.3:

  1. Jun 16, 2016 | laravel, laravel 5.3, echo, websockets
  2. Jun 27, 2016 | laravel, laravel 5.3
  3. Jun 29, 2016 | laravel, laravel 5.3, eloquent
  4. Jul 6, 2016 | laravel, laravel 5.3
  5. Jul 8, 2016 | laravel, laravel 5.3, eloquent
  6. Jul 25, 2016 | laravel, laravel 5.3
  7. Jul 26, 2016 | laravel, laravel 5.3
  8. Jul 27, 2016 | laravel, laravel 5.3, laravel scout, laravel passport, mailable
  9. Jul 27, 2016 | laravel, laravel 5.3, routing
  10. Jul 29, 2016 | laravel, laravel 5.3, laravel scout
  11. Jul 30, 2016 | laravel, laravel 5.3, laravel passport, oauth
  12. Aug 5, 2016 | laravel, laravel 5.3, mail, laravel mailables
  13. Aug 8, 2016 | laravel, laravel 5.3
  14. Oct 19, 2016 | laravel, laravel 5.3, laravel notifications, notifications
  15. Dec 21, 2016 | laravel, laravel 5.3, vuejs, vueify, authorization
  16. Dec 21, 2016 | laravel, laravel 5.3, queues
  17. Jan 30, 2017 | laravel, laravel 5.3, artisan

Subscribe

Quick links to fresh content, and more thoughts that don't make it to the blog