Home > Back-end >  Laravel Imports: How to replace imported row value by id?
Laravel Imports: How to replace imported row value by id?

Time:04-20

So i have this code:

PengajuanDetailController.php

public function import(Request $request){
    $file = $request->file('file');
    $namaFile = $file->getClientOriginalName();
    $file->move('DataDetailPengajuan', $namaFile);

    Excel::import(new SubmissionDetailImport, public_path('/DataDetailPengajuan/'.$namaFile));
    return redirect()->back()->with("status", ["status" => true, "message" => "Success importing detail"]);
}

SubmissionDetailImport.php

<?php

namespace App\Imports;

use App\SubmissionDetail;
use Maatwebsite\Excel\Concerns\ToModel;

class SubmissionDetailImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new SubmissionDetail([
            'submission_id' => $row[1],
            'nama_barang' => $row[2],
            'image_path' => $row[3],
            'jumlah' => $row[4],
            'harga_satuan' => $row[5],
            'harga_total' => $row[6],
            'keterangan' => $row[7],
        ]);
    }
}

I wanted to make the imported row value of 'submission_id' equal to an id,

for example: http://127.0.0.1:8000/pengajuan/4/

the row value of 'submission_id' becomes 4 of the "/4/" instead of the original imported value, how to do?

CodePudding user response:

You can simply pass your Url parameter, through to the importer.

public function import(Request $request, $submissionId) {
    ...

     Excel::import((new SubmissionDetailImport)->setSubmissionId(submissionId), public_path('/DataDetailPengajuan/'.$namaFile));

Now we are needing the logic on the Excel Importer class. Add it as a property and define a setter for it.

class SubmissionDetailImport implements ToModel
{
    private $submissionId;

    public function setSubmissionId($submissionId) {
        $this->submissionId = $submissionId;
    }

    public function model(array $row)
    {
        return new SubmissionDetail([
            'submission_id' => $this->submissionId,
            'nama_barang' => $row[2],
            'image_path' => $row[3],
            'jumlah' => $row[4],
            'harga_satuan' => $row[5],
            'harga_total' => $row[6],
            'keterangan' => $row[7],
        ]);
    }
}
  • Related