Upserting with Laravel's Eloquent ORM
In Laravel's Eloquent Object-Relational Mapping (ORM), it's often necessary to create a new record if it doesn't exist, or update an existing record if it does.
What is Upserting?
Upserting is a term used to describe the combination of insert and update operations into a single command. In the context of a database, upserting allows you to perform either an insert or update operation based on whether or not a record with specific criteria exists in the table.
Performing Upsert Operations
In Laravel Eloquent, upserting can be achieved using the firstOrNew method. This method takes an array of criteria as its argument and returns either an existing model if a record matching the criteria is found, or a new model instance if no matching record exists.
Example: Upserting a User Record
Consider a scenario where you want to create a new user if one doesn't exist, or update an existing user if one does. Here's an example:
<code class="php">$user = User::firstOrNew(array('name' => Input::get('name'))); $user->foo = Input::get('foo'); $user->save();</code>
In this example, the firstOrNew method checks if a User with the specified name already exists in the database. If it exists, the existing model is returned. Otherwise, a new model instance is created and returned.
Updated Documentation Link:
For the latest information on upserting in Laravel, refer to the official documentation here: [Updated Docs Link]
The above is the detailed content of How to Perform Upsert Operations Using Laravel\'s Eloquent ORM?. For more information, please follow other related articles on the PHP Chinese website!