【问题标题】:how to return variable in excel import如何在excel导入中返回变量
【发布时间】:2021-06-21 04:51:35
【问题描述】:

我需要返回控制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 导入中返回变量的方法。感谢您的帮助。

【问题讨论】:

    标签: php laravel laravel-excel


    【解决方案1】:

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

    首先,在 Import 类中创建一个公共变量$product_ids,为其分配所有 id

    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 类变量,如下所示。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-20
      • 2023-03-19
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 2021-11-08
      • 2021-06-05
      相关资源
      最近更新 更多