2

I need to return to controlling the id of the products entered by the excel import.

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

I have not found a way to return variables in excel import. Thanks for your help.

1 Answer 1

2

You can do this by public variable of ProductImport class and then use it in your Controller.

First, create one public variable $product_ids in Import class, assign it all 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;
    }
}

Now you can use the Import class variable in your Controller as below.

$import->product_ids;

Full code:

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.