Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Laravel – import excel sheet into database in multiple table

In this tutorial I will share how to (import excel sheet into database in multiple table) , we need to follow some simple steps,

Below this code, we have 2 models

1. Apply Student 2. Parents Details
in our excel sheet we have some student data and parent data, or we have 2 different tables in database student or parent) at first we save student table then we get last inserted id , and then we save the last inserted id (primary key) into parent table as foreign key

Laravel Maatawebsite Excel Package complete Documentation : click here

laravel maatawebsite import excel data into multiple tables
<?php
namespace App\Imports;
use Maatwebsite\Excel\Facades\Excel;
use App\Model\Frontend\ApplyStudent;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\Importable;
use App\Model\Admin\ParentsDetaills;


class StudentImport implements ToCollection,WithHeadingRow,WithValidation
{
    public function collection(Collection $rows)
    {

        foreach ($rows as $row)
        {
          
                $studentDetail =  ApplyStudent::create([
                'stu_unique_id'   => '#STU'.rand(111,99999),
                'stu_name'        => $excelRow['stu_name'],
                'stu_email'       => $excelRow["stu_email"],
                'stu_dob'         => $excelRow["stu_dob"],
                'stu_age'         => $excelRow["stu_age"],
                'stu_qualified_class' => $excelRow["stu_qualified_class"],
                'username'        =>  $excelRow['stu_username'] ,
                'password'        => Hash::make($excelRow['stu_password']),
                'stu_status'      => '1',
            ]);

            $ParentDetails =  ParentsDetaills::create([
                'unique_id'            =>  '#Par'.rand(111,99999),
                'father_name'          =>  $excelRow["father_name"],
                'student_id'           =>  $studentDetail->id,
                'father_occupation'    =>  $excelRow["father_occupation"],
                'father_qualifaction'  =>  $excelRow["father_qualifaction"],
                'father_email'         =>  $excelRow["father_email"],
                'mother_name'          =>  $excelRow["mother_name"],
                'mother_occupation'    =>  $excelRow["mother_occupation"],
                
            ]);
        }
    }
}

so, in this tutorial we have learnt how to (import excel sheet into database in multiple table)

Read also : How to validate excel sheet data in laravel ?