Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

davy_yg's avatar
Level 27

Update or create a new row?

EditProductForm.php

	//Foreach Category that is selected
    if (request('prod_cat') != null) {
        foreach (request('prod_cat') as $cat) {
            ProductsMeta::create([
              'prod_id' => request('prod_id'),
              'prod_meta_type' => 1,
              'value' => $cat
            ]);
        }
    }

Should this create a new row in the database or update the existing one?

0 likes
7 replies
tykus's avatar

create will always create a new record.

How would you know that ProductMeta record already existed; updateOrCreate would need to uniquely identify a records to be updated?

davy_yg's avatar
Level 27

There is one strange thing about this code. This is someone else code that is used to edit / update existing record.

I tested the code, my updating the product meta category and it literally changes without adding a new record.

tykus's avatar
tykus
Best Answer
Level 104

@davy_yg that should not be the case unless create has been overridden. If you want to update an existing record, then you need to first locate that record, e.g.

$productMeta = ProductMeta::where('foo', request('foo')->first();
if ($productMeta) {
		$productMeta->update([/* new attributes */]);
} else {
		$productMeta = ProductMeta::create([/* new attributes */]);
}

Thankfully, this is a one-step process using updateOrCreate where the first array locates the record, and both arrays are merged to set the attributes :

ProductMeta::updateOrCreate(['foo' => request('foo')], [/* new attributes */]);

In either case, a record is first located; this is not the case with the code you shared (assuming Eloquent create method).

Snapey's avatar

i doubt that

check the record id

davy_yg's avatar
Level 27

tables: products_metas

	prod_meta_id 
	47
	48

	prod_id
	1
	2

	prod_meta_type
	1
	2

	value
	1
	1

I tested by changing it's value the other remains the same.

tykus's avatar

The only way an INSERT query will UPDATE an existing record is INSERT... ON DUPLICATE KEY UPDATE SQL statement - this is not Eloquent's behaviour however.

Can you check if create has been overridden???

I tested by changing it's value the other remains the same.

EDIT what do you mean? Before the operation, both of these records exist or no???

davy_yg's avatar
Level 27

I found the missing link:

ProductsMeta::where('prod_id', request('prod_id'))->delete();

//Foreach Category that is selected
    if (request('prod_cat') != null) {
        foreach (request('prod_cat') as $cat) {
            ProductsMeta::create([
              'prod_id' => request('prod_id'),
              'prod_meta_type' => 1,
              'value' => $cat
            ]);
        }
    }

It deletes the records of that particular product id before creating a new one.

Please or to participate in this conversation.