Customizing additional parameters in FirstOrCreate in Laravel 5.3
This is a series of posts on New Features in Laravel 5.3.
!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:
-
Jun 16, 2016 | laravel, laravel 5.3, echo, websockets
-
Jun 27, 2016 | laravel, laravel 5.3
-
Jun 29, 2016 | laravel, laravel 5.3, eloquent
-
Jul 6, 2016 | laravel, laravel 5.3
-
Jul 8, 2016 | laravel, laravel 5.3
-
Jul 8, 2016 | laravel, laravel 5.3, eloquent
-
Jul 25, 2016 | laravel, laravel 5.3
-
Jul 26, 2016 | laravel, laravel 5.3
-
Jul 27, 2016 | laravel, laravel 5.3, routing
-
Jul 27, 2016 | laravel, laravel 5.3, laravel scout, laravel passport, mailable
-
Jul 29, 2016 | laravel, laravel 5.3, laravel scout
-
Jul 30, 2016 | laravel, laravel 5.3, laravel passport, oauth
-
Aug 5, 2016 | laravel, laravel 5.3, mail, laravel mailables
-
Aug 8, 2016 | laravel, laravel 5.3
-
Oct 19, 2016 | laravel, laravel 5.3, laravel notifications, notifications
-
Dec 21, 2016 | laravel, laravel 5.3, vuejs, vueify, authorization
-
Dec 21, 2016 | laravel, laravel 5.3, queues
-
Jan 30, 2017 | laravel, laravel 5.3, artisan