Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update all records in a table with Eloquent?

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());

.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

.

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

>Solution :

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);
}

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading