Skip to content
Advertisement

Laravel Imports: How to replace imported row value by id?

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 AppImports;

use AppSubmissionDetail;
use MaatwebsiteExcelConcernsToModel;

class SubmissionDetailImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return IlluminateDatabaseEloquentModel|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?

Advertisement

Answer

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],
        ]);
    }
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement