Laravel Excel Multiple table primary_id save to another table as a foreign_id

Viewed 3242

I can successfully import Excel Data in Laravel and Insert into Database multiple tables. I am using maatwebsite/excel version 3 composer package and laravel version 5.8

How can I insert mamber_id value in licence_application table (foreign id) which is member table primary id.

ImportClass file:

class UsersImport implements ToCollection
{
    /**
     * @param Collection $collection
     */
    public function collection(Collection $rows)
    {

        foreach ($rows as $row){
            Member::create([
                    'full_name'     => $row[0],
                    'father_name'   => $row[1],
                    'mother_name'   => $row[2],
                    'cell_number'   => $row[3],
            ]);
            LicenceApplication::create([
                'member_id' => ???
                'licence_category_name' => $row[4],
            ]);
            LicenceSuccess::create([
                'application_type' => $row[5],
            ]);
        }        

    }
}

Controller file: ImporExcelController.php

public function import(Request $request)
{
     $this->validate($request, [
        'select_file' => 'required|mimes:xls,xlsx'
     ]);

     $path = $request->file('select_file')->getRealPath();

     $data = Excel::import(new UsersImport, $path);

     return back()->with('success', 'Import data successfully!');
}

Excel file screenshot: https://imgur.com/a/XhxBRpW

Please help me how to solve this issue?

1 Answers

I solve this issue here is the code.

foreach ($rows as $row){
        $memberId = Member::create([
            'full_name'     => $row['full_name'],
            'father_name'   => $row['father_name'],
            'mother_name'   => $row['mother_name'],
            'cell_number'   => $row['cell_number'],
        ]);
        $applicationId  = LicenceApplication::create([                
            'member_id'             => $memberId->member_id,
            'licence_category_name' => $row['licence_category_name'],
        ]);
        LicenceSuccess::create([
            'member_id'         => $memberId->member_id,
            'application_id'    => $applicationId->application_id,
            'application_type'  => $row['application_type'],
        ]);
    }
Related