How to Perform Upsert Operations Using Laravel\'s Eloquent ORM?

Mary-Kate Olsen
Release: 2024-10-20 08:44:02
Original
480 people have browsed it

How to Perform Upsert Operations Using Laravel's Eloquent ORM?

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!