djhru
djhru

Reputation: 336

How to get imported row id in Laravel Excel

I am using Laravel Excel and I need to get id of imported rows during import.

code

public function model(array $row)
{
    $link = new Link([
      'site_name'    => $row['site_name'],
    ]);

    $name = explode('-', $row['site_name']);
    $site = Site::whereIn('name', $name)->pluck('id');
    $link->sites()->sync($site, false);  // this `$link` can't get id of imported row

    return $link;
}

Error

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'link_id' cannot be null (SQL: insert into link_sites (link_id, site_id) values (?, 14))

Any idea?

Upvotes: 1

Views: 2431

Answers (1)

djhru
djhru

Reputation: 336

Solved

I've changed my function to use onEachRow and it's working now.

public function onRow(Row $row)
{
    $rowIndex = $row->getIndex();
    $row = $row->toArray();
    
    $link = Link::create([
        'site_name'    => $row['site_name'],
    ]);

    $name = explode('-', $row['site_name']);
    $site = Site::whereIn('name', $name)->pluck('id');
    $link->sites()->sync($site, false);
}

Document

Upvotes: 4

Related Questions