Skip to content

Upserting Data

Jason Napolitano edited this page Sep 16, 2023 · 9 revisions

Using the ORM

DatabaseFactory gives developers the ability to upsert data. This means that we can pass an array of data into a method and either have that data create a new record (insert) or update an existing record (update). In order to create or update data using the ORM system, you need to add the HasUpsert trait to your Entity

class User extends DatabaseFactory\Entity
{
    use DatabaseFactory\ORM\HasUpsert;
}

From here, you can very easily call the uspert() method from the entity you're working with to either add a new record, or modify an existing one.

$data = [
    'name'     => 'John Smith',
    'email'    => '[email protected]',
    'password' => Str::bcrypt('password'),
];

# add a new record
User::upsert(data: $data);

# OR

# modify an existing record by passing
# through its ID
User::upsert(data: $data, id: 10);

Using a callback

The upsert() method also accepts a callback function as the callback parameter. This will return an entity object of the record you are working with.

$data = [
    'name'     => 'John Smith',
    'email'    => '[email protected]',
    'password' => Str::bcrypt('password'),
];

User::upsert(data: $data, callback: function($user) {
    echo $user->name; // 'John Smith'
});

Using Entities

Creating data

Creating new data and adding it to your database is extremely simple. All we need to do is create a new entity object, and assign values to its fields. From there, we call the save() method to save the record.

# create a new entity object
$user = new User();

# assign values to the entities properties
$user->name = 'Georges St. Pierre';
$user->email = '[email protected]';
$user->password = Str::bcrypt('password');

# save the record
$user->save();

Modifying data

Updating a record is virtually identical to creating a new one. The main difference here is that we will be passing an ID into the constructor of the entity object which represents the record we are working with

# create a new entity object and pass the ID 
# into the constructor
$user = new User(15);

# assign values to the entities properties
$user->name = 'Anderson Silva';
$user->email = '[email protected]';
$user->password = Str::bcrypt('password');

# save the record
$user->save();
Clone this wiki locally