Laravel updateOrCreate, firstOrNew, firstOr and firstOrCreate Methods

Laravel supports an updateOrCreate in-built method to do this in simple step by step. Such as the firstOrCreate in-built method, updateOrCreate persists the laravel model, therefor no required to call save() method. Also You can here come across any types of the dev. situations where you want to simply update an existing laravel model or create a fresh new laravel model if none exists.

Also You can read my prev Articles : findorfail laravel

laravel Laravel 7/6 updateOrCreate method

in Laravel The updateOrCreate in-built method attempts to find a Model similar the constraints passed as the first argument. If a similar Model is found, it will all the data update the match with the attributes passed as the second argument. If no similar Model is found a new Model will be created with both the data constraints passed as the first argument as well as the attributes passed as the second argument.

Read Also:  Remove null values from array in PHP

Syntax of the updateOrCreate()

$getData = App\Yourmodelname::updateOrCreate(
    ['param1' => 'value1', 'param2' => 'value2'],
    ['param3' => value3, 'param4' => value4]
);

You can refactor this part of source code:

$member = Member::where('member_ship_code', request('member_ship_code'))->first();

if ($member !== null) {
    $member->update(['name' => request('name')]);
} else {
    $member = Member::create([
      'member_ship_code' => request('member_ship_code'),
      'name' => request('name'),
    ]);
}

// Do other things with the Member

To this using the update or create in-built method:

$member = Member::updateOrCreate(
    ['member_ship_code' =>  request('member_ship_code')],
    ['name' => request('name')]
);

// Do other things with the Member

laravel firstOr method

I recently found the firstOr in-built laravel method while source-diving. The firstOr in-built laravel method retrieves the first Model from a simple Eloquent query, or if no similar Model is found, it will call a simply callback passed. This can be really helpful if you required to perform extra onther phases when creating a member or want to do something other than creating a new member:

Read Also:  Create Dynamic Image Fancybox Gallery with jQuery, PHP & MySQL

$member = Member::where('member_ship_code', request('member_ship_code'))->firstOr(function () {
    $account = Account::create([ //... ]);

    return Member::create([
        'account_id' => $account->id,
        'member_ship_code' => request('member_ship_code'), 
    ]);
});

laravel firstOrCreate method

The firstOrCreate method is very similar to the firstOrNew in-built method. It tries to find a model similar the attributes you pass in the first argument. If a laravel model is not found, it automatically creates as well as store and saves a new laravel Model after applying any attributes passed in the other argument:

$member = Member::firstOrCreate(
    ['member_ship_code' =>  request('member_ship_code')],
    ['name' => request('name')]
);

// No call to $member->save() needed

laravel firstOrNew method

The firstOrNew in-built method is very helpful for finding the first laravel Model that matches some data constraints or creating a new fresh one if there isn’t one that matches those Data constraints.

Read Also:  JQuery Ajax Dynamic Treeview using PHP MySQL Example

You can take a part of source code that looks shuch this:

$member = Member::where('member_ship_code', request('member_ship_code'))->first();

if ($member === null) {
    $member = new Member(['member_ship_code' => request('member_ship_code')]);
}

$member->name = request('name');

$member->save()

And turn it into this:

$member = Member::firstOrNew(['member_ship_code' =>  request('member_ship_code')]);

$member->name = request('name');

$member->save()

You may also pass an array of extra other attributes to set as the second argument if no existing laravel Model is found:

$member = Member::firstOrNew(
    ['member_ship_code' =>  request('member_ship_code')],
    ['name' => request('name')]
);

$member->save();

I hope you get an idea about laravel updateorcreate relationship.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1. Read Also:  PHP woocommerce_after_shop_loop_item Examples
  2. Read Also:  jQuery AJAX Pagination in PHP Without Page Refresh Example
  3. Read Also:  Top 5 Best php PDF Generation libraries
  4. Read Also:  Laravel AJAX Live Search Example
  5. Read Also:  How to get site URL in Laravel 6?
  6. Read Also:  alias in sql
  7. Read Also:  PHP Rest API Framework List with Features
  8. Read Also:  How To Configure Supervisor For Laravel 5/6/7 Queue Jobs?
  9. Read Also:  laravel Add cascade on delete (ON DELETE CASCADE)
  10. Read Also:  Laravel Group By Count Multiple Columns
CLOSEX