Laravel 7.6 maatawebsite 3.1 excel 导入不在数据表中保存数据

Laravel 7.6 maatawebsite 3.1 excel import not saving data in datatable

我一直在尝试上传 excel 到我的数据 - table 但它不起作用。我正在上传成功消息数据,但它没有保存 excel 个条目。

我也遵循了这个链接的说明: https://www.studentstutorial.com/laravel/import https://www.webslesson.info/2019/02/import-excel-file-in-laravel.html

这是我的控制器:

//Save the File
    if($request->hasFile('file'))
    {
        // Get the file with extension
        $filenameWithExt = $request->file('file')->getClientOriginalName();
        //Get the file name
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        //Get the ext
        $extension = $request->file('file')->getClientOriginalExtension();
        //File name to store
        $fileNameToStore = $filename.'_'.time().'.'.$extension;
        //Upload File
        $path = $request->file('file')->storeAS('public/excels', $fileNameToStore);


    }

    $this->validate($request, [
        'file' => 'required|mimes:xlsx,xls',
    ]);


    $data = Excel::import(new Product, $path);

    foreach ($data as $row) {

        $arr[] = [
            'Title' => $row->title,
            'Text' => $row->text,
            'Slug' => $row->slug,
            'Brand_id' => $row->brand_id,
            'Category_id' => $row->category_id,
            'Image' => $row->image,
        ];

            if (!empty($arr)) {
                DB::table('products')->insert($arr);
            }
        }


    return back()->with('success', 'Products Added');

我的表格:

<form role="form" method="POST" action="{{ action('ProductsController@import')}}" enctype="multipart/form-data">
                            @csrf
                            <div class="input-group mb-3 shadow">
                                <input type="file" name="file" class="btn btn-dark" title="Select File">
                                <button type="submit" class="btn btn-success rounded-0">Upload</button>
                            </div>
                        </form>

一段时间后我能够解决它 myself.I 创建了一个新的 Import Controller 并在 ProductsController@import 中进行了此更改

我在控制器中所做的更改:

$products = Excel::toArray(new ProductsImport(), $request->file('file'));

    foreach($products[0] as $row) {
        //  dd($row[1].' '.$row[2]);
        $arr[] = [
            // If uncomment this id from here, remove [0] from foreach
            // 'id' => $row[0], 
            'image' => $row[1],
            'title' => $row[2],
            'slug' => $row[3],
            'text' => $row[4],
            'brand_id' => $row[5],
            'category_id' => $row[6],
        ];
    }
    // dd($products);

    if(!empty($arr)){
        DB::table('products')->insert($arr);
    }

    return back()->with('success', 'Products Added');

现在,正在将文件保存到 public/excels 并将数据导入数据表。