Home > Software design >  How to update all records in a table with Eloquent?
How to update all records in a table with Eloquent?

Time:07-23

Solution

foreach($request->all() as $record){
    EventViews::query()->updateOrCreate(['id'=>$record['id']], $record);
}

Question

How do I update a whole table by passing a request array? It should update existing rows and create new ones if id doesn't exist. If possible without having to loop over the whole table.

Attempts that don't work:

EventViews::query()->updateOrCreate($request->all());

.

DB::transaction(function ($request) {
    foreach ($request->all() as $record) {
        EventViews::updateOrCreate($record);
    }
});

.

$model = new EventViews($request->all());
$model->fill($request->all())->save();

CodePudding user response:

assuming your request payload looks something like

records[]=[id=1,name=foo,description=foo,c=1]&
records[]=[id=2,name=bar,description=bar,c=1]&
...

you could loop over it like:

$input = $request->input('records');
foreach($input as $record){
    EventViews::query()->updateOrCreate(['id'=>$record['id']],$record);
}

if your request looks like:

1=[name=foo,description=foo,c=1]&
2=[name=bar,description=bar,c=1]&
...

where the parameter name is the id, then you could use:

$input = $request->input();
foreach($input as $key => $record){
    EventViews::query()->updateOrCreate(['id'=>$key],$record);
}

CodePudding user response:

you can use this method :

$flight = Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99, 'discounted' => 1]
);

or

Flight::upsert([
    ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
    ['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], ['departure', 'destination'], ['price']);

for get more information see this link: https://laravel.com/docs/9.x/eloquent#upserts

CodePudding user response:

updateOrCreate receives 2 parameters, the first is the constrains and the second is the data.
I don't know your request structure, but it's good practice verify it before throwing it into your database.
Example:
Model::query()->updateOrCreate(
['my_column' => $request->input('my_column')],
[*array of column/values of what should be updated*]
)]

If exists a Model with given my_column value, it will update it's value with the associative array passed on the second argument, otherwise it will create a new entry.

  • Related