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

Ap3twe's avatar

Updating Database using updateOrCreate method

Hey, am inserting images to a database. I tried updateOrCreate but It replaces every record in the database with the new data. I do not want to update just insert data to tables I assigned null. I tried two methods. one work perfectly I get the file temp-name in the database, but for me to get the file name, I triedupdateOrCreate, and create method but it deletes all records in the schema.

This deletes all my records

 $project = Project::updateOrCreate(array_merge(request([  'labphotofiles', 'labstlfiles', 'user_id',
      
         ]),
        //  bottom I have used array_merge to store the user id
         [
         'user_id'=>auth()->id(),
         'labphotofiles' => $labphotofileNameToStore,
         'labstlfiles' => $labstlfileNameToStore,
          ]));

Another method I used is save method. This one works, adds the data but how can I attach the filename to it?

$project->labphotofiles = request('labphotofiles');
$project->labstlfiles = request('labstlfiles');
 $project->save();
0 likes
4 replies
Ap3twe's avatar
Ap3twe
OP
Best Answer
Level 5

I solved it. Anybody in the same situation, I did not know there is a fill method. In the laravel docs https://laravel.com/docs/5.8/eloquent#inserts it is hidden there lol

$project->fill(['labphotofiles'=> $labphotofileNameToStore]);
$project->fill(['labstlfiles' => $labphotofileNameToStore]);
$project->save();
1 like
Snapey's avatar

Your example is no different to

$project->labphotofiles = $labphotofileNameToStore;
$project->labstlfiles = $labphotofileNameToStore;
$project->save();

fill inserts an array of values, so your way you could have done;

$project->fill([
        'labphotofiles'=> $labphotofileNameToStore,
        'labstlfiles' => $labphotofileNameToStore
    ])->save();

But neither of these is anything like updateOrCreate so I'm puzzled how you start thinking you need updateOrCreate and then use this?

Ap3twe's avatar

@SNAPEY - I tried the first example before, It gave me an error. It throws undefined variable. I will utilize the second example. I think is clean. My problem was trying to use the create method but was giving me user constraint error. So I was reading the docs to find alternative, I thought the updateOrCreate will insert the values if it doesn't have a record in the fields. What is the use of the updateOrCreate Method?

Snapey's avatar

updateOrCreate requires two parameters. The first is a set of key value pairs which act as a where statement for the record that should be updated. The second set of parameters are the values to be inserted in the new or existing record

Your code was seemingly trying to use the whole request object as the where conditions. Any fields in there that are not columns in the database will throw an error

1 like

Please or to participate in this conversation.