UPDATE VIA CSV LARAVEL

Asked

Viewed 47 times

1

I have this parameter to import data via CSV and I want to know how to create the UPDATE function based on the CODE field.

public function importEstoque(Request $request)
{
    $validator = Validator::make($request->all(), [
        'file' => 'required'
    ]);
    if ($validator->fails()) {
        return redirect()
            ->back()
            ->withErrors($validator);
    }
    $file = $request->file('file');
    $csvData = file_get_contents($file);
    $rows = array_map("str_getcsv", explode("\n", $csvData));
    $header = array_shift($rows);
    foreach ($rows as $row) {
        $row = array_combine($header, $row);
        Estoque::insert([
            'codigo' => $row['Código'],
            'nome' => $row['Produto'],
            'estoque' => $row['Qtd.'],
        ]);
    }
}
  • I didn’t quite understand the question I could explain better ?

  • If that’s what I’m thinking, you want to do another method to update, and update based on code ?

  • In the box it would not be for the ID, but for the CODE field that in this application represents the product’s barcode. Then the user will import a file with the Barcode, Product and Quantity, with this, update at the base. It is possible to do this?

  • In that same important function ?

  • Could be a new function, I put it as an example.

  • You can do one that updates and inserts at the same time, but I will create one just to update based on this import you made

  • Perfect. Thanks for the support/

  • Try it on and tell me.

Show 3 more comments

1 answer

2


I made the method to update the product name and the stock, based on the code already registered in the system.

public function importUpdateEstoque(Request $request)
{
    $validator = Validator::make($request->all(), [
        'file' => 'required'
    ]);
    if ($validator->fails()) {
        return redirect()
            ->back()
            ->withErrors($validator);
    }
    $file = $request->file('file');
    $csvData = file_get_contents($file);
    $rows = array_map("str_getcsv", explode("\n", $csvData));
    $header = array_shift($rows);
    foreach ($rows as $row) {
        $row = array_combine($header, $row);
        Estoque::where('codigo', $row['Código'])
            ->update([
                'nome' => $row['Produto'],
                'estoque' => $row['Qtd.'],
            ]);
    }
}

If you need to set more conditions just add others where(); and if you wanted to update more columns and just add inside the array inside update();.

  • It worked out/ Thank you very much for the support!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.