Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

felloz's avatar

Laravel Excel - Import CSV data relationed to another table

I need to import some rows from a CSV file to a table, but this rows are relationed to another table to create the realtion of two registers. Thos relations are created by a field ID autoincremental.

I have 3 tables involved

  1. tbl_party Relationed tbl_party_employee,
  2. tbl_employee Relationed to tbl_party_employee,
  3. tbl_party_employee The table where i created the relations between 2 tables.

This is the method where my rows are setted to register

 public function model(array $row)
    {
       
          return new Contact(
              [
                    'user_id' => $this->userId,
                    'subscriber_email'     => $row[0],
                    'subscriber_name'      => $row[1],
                    'subscriber_lastname'  => $row[2],
                    'subscriber_phone'     => $row[3],
                    'whatsapp_number'      => $row[4],
                    'birth_date'    => $this->formatDateExcel($row[5]),
                    'custom_field1' => $row[6],
                    'custom_field1' => $row[7],
                    'custom_field1' => $row[8],
                    'custom_field4' => $row[9],
              ]
          );   
    }

Any help to do this is appreciated.

0 likes
1 reply
felloz's avatar
felloz
OP
Best Answer
Level 1

To anyone that in the future has the same problem, the correct way to doit isn't with models, instead you need to use collections: https://docs.laravel-excel.com/3.1/imports/collection.html

namespace App\Imports;

use App\User;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class UsersImport implements ToCollection
{
    public function collection(Collection $rows)
    {
        foreach ($rows as $row) 
        {
            User::create([
                'name' => $row[0],
            ]);
        }
    }
}
´´´
1 like

Please or to participate in this conversation.