{"id":11157,"date":"2021-12-09T10:00:00","date_gmt":"2021-12-09T01:00:00","guid":{"rendered":"https:\/\/www.gigas-jp.com\/appnews\/?p=11157"},"modified":"2021-12-08T17:19:57","modified_gmt":"2021-12-08T08:19:57","slug":"different-laravel-methods-firstornew-firstorcreate-firstor-and-updateorcreate","status":"publish","type":"post","link":"https:\/\/www.gigas-jp.com\/appnews\/archives\/11157","title":{"rendered":"Different Laravel methods firstOrNew, firstOrCreate, firstOr, and updateOrCreate"},"content":{"rendered":"\n<p> Standard methods for creating Eloquent Models like&nbsp;<code>make()<\/code>,&nbsp;<code>create()<\/code>,&nbsp;<code>update<\/code>, and&nbsp;<code>save()<\/code>. Laravel includes some other methods are that also really useful for creating and updating Models that I feel don\u2019t get enough attention.&nbsp;So in this article, I\u2019d like to go over some of these additional methods and explain how they might be useful. <\/p>\n\n\n\n<p><\/p>\n\n\n\n<p> <strong>1<\/strong>. <strong>firstOrNew<\/strong> <\/p>\n\n\n\n<p id=\"3730\">The&nbsp;<code>firstOrNew<\/code>&nbsp;method is really useful for finding the first Model that matches some constraints or making a new one if there isn\u2019t one that matches those constraints.<\/p>\n\n\n\n<p id=\"8d78\">You can take a piece of code that looks like this:<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p>$user = User::where(&#8216;email,&#8217;$request-&gt;email)-&gt;first();<\/p>\n\n\n\n<p>if($user === null){<\/p>\n\n\n\n<p>    $user = new User([ &#8216;email&#8217; =&gt; $request-&gt;email ]);<\/p>\n\n\n\n<p>    $user-&gt;name = $request-&gt;name;<\/p>\n\n\n\n<p>    $user-&gt;save();<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>And turn it into this:<\/p>\n\n\n\n<p>$user = User::firstOrNew( [ &#8216;email&#8217; =&gt; $request-&gt;email ] );<\/p>\n\n\n\n<p>    $user-&gt;name = $request-&gt;name;<\/p>\n\n\n\n<p>    $user-&gt;save();<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p>You may also pass an array of additional attributes to set as the second parameter if no existing Model is found:<\/p>\n\n\n\n<p>$user = User::firstOrNew([&#8216;email&#8217; =&gt; request(&#8216;email&#8217;)],[&#8216;name&#8217; =&gt; request(&#8216;name&#8217;)]);<\/p>\n\n\n\n<p>$user-&gt;save();<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p> <strong>2<\/strong>.<strong>firstOrCreate<\/strong> <\/p>\n\n\n\n<p> I recently found the&nbsp;<code>firstOr<\/code>&nbsp;method while source-diving. The&nbsp;<code>firstOr<\/code>&nbsp;method retrieves the first Model from a query, or if no matching Model is found, it will call a callback passed. This can be really useful if you need to perform extra steps when creating a user or want to do something other than creating a new user: <\/p>\n\n\n\n<p> $user = User::where(&#8216;email,&#8217;$request-&gt;email)-&gt;firstOr(function(){<\/p>\n\n\n\n<p>                   $account = Account::create([<\/p>\n\n\n\n<p>                         return User::create([<\/p>\n\n\n\n<p>                              &#8216;account_id&#8217; =&gt; $account-&gt;id,<\/p>\n\n\n\n<p>                               &#8216;email&#8217; =&gt; $request-&gt;email<\/p>\n\n\n\n<p>                          ]);<\/p>\n\n\n\n<p>                    ]);<\/p>\n\n\n\n<p>            }); <\/p>\n\n\n\n<p><\/p>\n\n\n\n<p> <strong>3<\/strong>.<strong>firstOr<\/strong><\/p>\n\n\n\n<p id=\"00ed\">I recently found the&nbsp;<code>firstOr<\/code>&nbsp;method while source-diving. The&nbsp;<code>firstOr<\/code>&nbsp;method retrieves the first Model from a query, or if no matching Model is found, it will call a callback passed. This can be really useful if you need to perform extra steps when creating a user or want to do something other than creating a new user:<\/p>\n\n\n\n<p> $user = User::where(&#8216;email,&#8217;$request-&gt;email)-&gt;firstOr(function(){<\/p>\n\n\n\n<p>   $account = Account::create([<\/p>\n\n\n\n<p>       return User::create([<\/p>\n\n\n\n<p>           &#8216;account_id&#8217; =&gt; $account-&gt;id,<\/p>\n\n\n\n<p>           &#8216;email&#8217; =&gt; $request-&gt;email<\/p>\n\n\n\n<p>       ]);<\/p>\n\n\n\n<p>   ]);<\/p>\n\n\n\n<p>}); <\/p>\n\n\n\n<p>  <strong>4.updateOrCreate<\/strong> <\/p>\n\n\n\n<p>The&nbsp;<code>updateOrCreate<\/code>&nbsp;method attempts to find a Model matching the constraints passed as the first parameter. If a matching Model is found, it will update the match with the attributes passed as the second parameter. If no matching Model is found a new Model will be created with both the constraints passed as the first parameter and the attributes passed as the second parameter.<\/p>\n\n\n\n<p>You can refactor this piece of code:<\/p>\n\n\n\n<p>  $user = User::where(&#8216;email,&#8217;$request-&gt;email)-&gt;first();<\/p>\n\n\n\n<p>if($user !== null){<\/p>\n\n\n\n<p>    $user-&gt;update([&#8216;name&#8217; =&gt; $request-&gt;name]);<\/p>\n\n\n\n<p>}else{<\/p>\n\n\n\n<p>   $user = User::create([<\/p>\n\n\n\n<p>      &#8216;email&#8217; =&gt; $request-&gt;email,<\/p>\n\n\n\n<p>      &#8216;name&#8217; =&gt; $request-&gt;name<\/p>\n\n\n\n<p>   ]);<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p>To this using the&nbsp;<code>updateOrCreate<\/code>&nbsp;method:<\/p>\n\n\n\n<p>   $user = User::updateOrCreate([<\/p>\n\n\n\n<p>      &#8216;email&#8217; =&gt; $request-&gt;email,<\/p>\n\n\n\n<p>      &#8216;name&#8217; =&gt; $request-&gt;name<\/p>\n\n\n\n<p>   ]);<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p>Tsuki<\/p>\n\n\n\n<p> <\/p>\n<div class='wp_social_bookmarking_light'>\n            <div class=\"wsbl_google_plus_one\"><g:plusone size=\"medium\" annotation=\"none\" href=\"https:\/\/www.gigas-jp.com\/appnews\/archives\/11157\" ><\/g:plusone><\/div>\n            <div class=\"wsbl_hatena_button\"><a href=\"\/\/b.hatena.ne.jp\/entry\/https:\/\/www.gigas-jp.com\/appnews\/archives\/11157\" class=\"hatena-bookmark-button\" data-hatena-bookmark-title=\"Different Laravel methods firstOrNew, firstOrCreate, firstOr, and updateOrCreate\" data-hatena-bookmark-layout=\"standard\" title=\"\u3053\u306e\u30a8\u30f3\u30c8\u30ea\u30fc\u3092\u306f\u3066\u306a\u30d6\u30c3\u30af\u30de\u30fc\u30af\u306b\u8ffd\u52a0\"> <img src=\"\/\/b.hatena.ne.jp\/images\/entry-button\/button-only@2x.png\" alt=\"\u3053\u306e\u30a8\u30f3\u30c8\u30ea\u30fc\u3092\u306f\u3066\u306a\u30d6\u30c3\u30af\u30de\u30fc\u30af\u306b\u8ffd\u52a0\" width=\"20\" height=\"20\" style=\"border: none;\" \/><\/a><script type=\"text\/javascript\" src=\"\/\/b.hatena.ne.jp\/js\/bookmark_button.js\" charset=\"utf-8\" async=\"async\"><\/script><\/div>\n            <div class=\"wsbl_twitter\"><a href=\"https:\/\/twitter.com\/share\" class=\"twitter-share-button\" data-url=\"https:\/\/www.gigas-jp.com\/appnews\/archives\/11157\" data-text=\"Different Laravel methods firstOrNew, firstOrCreate, firstOr, and updateOrCreate\" data-via=\"GIGASJAPAN_APPS\" data-lang=\"ja\">Tweet<\/a><\/div>\n            <div class=\"wsbl_facebook_like\"><div id=\"fb-root\"><\/div><fb:like href=\"https:\/\/www.gigas-jp.com\/appnews\/archives\/11157\" layout=\"button_count\" action=\"like\" width=\"100\" share=\"false\" show_faces=\"false\" ><\/fb:like><\/div>\n            <div class=\"wsbl_facebook_send\"><div id=\"fb-root\"><\/div><fb:send href=\"https:\/\/www.gigas-jp.com\/appnews\/archives\/11157\" colorscheme=\"light\" ><\/fb:send><\/div>\n    <\/div>\n<br class='wp_social_bookmarking_light_clear' \/>\n","protected":false},"excerpt":{"rendered":"<p>Standard methods for creating Eloquent Models like&nbsp;make(),&nbsp;create(),&nbsp;update, and&nbsp;save(). L [&hellip;]<\/p>\n","protected":false},"author":21,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[35],"tags":[],"acf":[],"_links":{"self":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts\/11157"}],"collection":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/users\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/comments?post=11157"}],"version-history":[{"count":2,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts\/11157\/revisions"}],"predecessor-version":[{"id":11161,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/posts\/11157\/revisions\/11161"}],"wp:attachment":[{"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/media?parent=11157"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/categories?post=11157"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gigas-jp.com\/appnews\/wp-json\/wp\/v2\/tags?post=11157"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}