如何在 excel 导入中 return 变量

how to return variable in excel import

我需要 return 控制通过 excel 导入输入的产品的 ID。

ProductImport.php

<?php
namespace App\Imports;

use App\Product;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class ProductImport implements  ToCollection {
    public function collection(Collection $rows) {
       foreach ($rows as $row) {
           $product = Product::create([
               'name' => $row[0],
               'detail' => $row[1]                
           ])->id;
       }
       return $product;
    }
}

ProductController.php

public function uploadProducts(Request $request) {
    $request->validate([
        'import_file' => 'required|file|mimes:xls,xlsx'
    ]);

    $path = $request->file('import_file');
    $import = new ProductImport;
    Excel::import($import, $path);
    //Here, how can I return the id of the products that were entered?
    return response()->json(['message' => 'uploaded successfully'], 200);
}

我还没有找到在 excel 导入中 return 变量的方法。感谢您的帮助。

您可以通过 ProductImportclass 的 public 变量来执行此操作,然后在您的控制器中使用它。

首先,在 Import class 中创建一个 public 变量 $product_ids,为其分配所有 ids

class ProductImport implements  ToCollection
{
    public $product_ids; // declare one public variable

    public function collection(Collection $rows)
    {
       foreach ($rows as $row) {

         // store created product ids as array
           $this->product_ids[] = Product::create([
               'name' => $row[0],
               'detail' => $row[1]
           ])->id;
       }

       return $product;
    }
}

现在您可以在控制器中使用 Import class 变量,如下所示。

$import->product_ids;

完整代码:

public function uploadProducts(Request $request)
{
    $request->validate([
        'import_file' => 'required|file|mimes:xls,xlsx'
    ]);

    $path = $request->file('import_file');

    $import = new ProductImport;

    Excel::import($import, $path);

    dd($import->product_ids); // it will return you an array

    return response()->json(['message' => 'uploaded successfully'], 200);
}