Home >Backend Development >PHP Tutorial >How to Insert or Update Records Efficiently Using Eloquent\'s firstOrNew() Method?
When working with databases, it's common to need to insert a new record if it doesn't exist or update an existing record if it does. In Laravel's Eloquent ORM, this can be done concisely using the firstOrNew() method.
$model = Model::firstOrNew($attributes);
If the record already exists in the database, the firstOrNew() method will return an instance of that model. You can then modify its attributes and save it using the save() method.
<code class="php">$user = User::firstOrNew(array('name' => Input::get('name'))); $user->foo = Input::get('foo'); $user->save();</code>
If the record doesn't exist in the database, the firstOrNew() method will create a new instance of the model with the specified attributes. It will then insert the record into the database when you call the save() method.
<code class="php">// Insert new record into database</code>
In the provided code snippet, the following approach is also used to insert a new record if it doesn't exist or update an existing record if it does:
<code class="php">$shopOwner = ShopMeta::where('shopId', '=', $theID) ->where('metadataKey', '=', 2001)->first(); if ($shopOwner == null) { // Insert new record into database } else { // Update the existing record }</code>
This approach involves first querying the database to retrieve the existing record. If no record is found, a new record is inserted. Otherwise, the existing record is updated.
For the latest information on the firstOrNew() method, refer to the updated documentation linked below.
[Updated Documentation Link](https://laravel.com/docs/8.x/eloquent)
The above is the detailed content of How to Insert or Update Records Efficiently Using Eloquent\'s firstOrNew() Method?. For more information, please follow other related articles on the PHP Chinese website!