Laravel 11 / Builder::addUniqueIdsToUpsertValues()

laravel 11 builder add unique ids to upsert values
12 May 2025

Definition of the function Builder::addUniqueIdsToUpsertValues()


The function addUniqueIdsToUpsertValues in the Laravel framework helps you to add unique identifiers to the values for upsert operations in the upsert function. One of the issues that may arise when importing data into the data repository is that duplicate values exist and in this case, only unique data should be imported.


In Laravel, upsert operations allow you to simultaneously update and insert data. For example, you can update a record if it exists and if it does not exist, you insert it. This way, developers can perform operations faster and more efficiently.


As adding unique identifiers to records can be a significant factor in the overall effectiveness of the program, the function addUniqueIdsToUpsertValues has been specifically designed for this purpose. This function allows you to ensure that identifiers during an update or new insert will not be duplicated.


By using this function, you can easily and without any complicated twists ensure that your data remains unique. This task can help reduce inconsistencies and improve the overall performance of the data repository.



$values = [
[ 'name' => 'example', 'email' => '[email protected]' ],
[ 'name' => 'test', 'email' => '[email protected]' ]
];

DB::table('users')->upsert(
$values,
['email'], // Unique by email
['name'] // Update name if exists
);

Explanation


$values: This variable contains an array of data that we want to add to the users table. Each record includes the name and email of the user.




DB::table('users')->upsert: This line indicates the call to the upsert function for the users table that will simultaneously insert and update the data.




['email']: This part specifies that the email field must be considered as the unique identifier of the records. This means if an email already exists, the corresponding record will be updated.




['name']: In this section, it is specified that if a record with the same email is found, only the name field of that record should be updated.

FAQ

?

What exactly does the function addUniqueIdsToUpsertValues do?

?

Why should we use upsert?

?

Can I define multiple fields as unique?