I am new to Laravel, I want to insert student details from xlsx file into mysql database. I'm using Laravel excel v3 to import excel files. It works fine. However, apart from inserting student details in 1 table, the same student ID record should be created in all related tables.
Example--> If you insert 1 student in the "student_details" table, you must create 1 record in the "oral" and "endsem" tables with the foreign key "student_id".
I have run the event to record these in the verbal table and the final table. Now the question is how to apply the event and how to get the student ID after creating the student to trigger the event. (Student ID will be the auto_increment value)
StudentImport -->
<?php namespace App\Imports; use App\Events\StudentCreated; use Illuminate\Support\Collection; use Maatwebsite\Excel\Concerns\ToModel; use Maatwebsite\Excel\Validators\Failure; use Maatwebsite\Excel\Concerns\Importable; use Maatwebsite\Excel\Concerns\SkipsOnFailure; use Maatwebsite\Excel\Concerns\WithValidation; use Maatwebsite\Excel\Concerns\SkipsFailures; use Maatwebsite\Excel\Concerns\WithHeadingRow; use App\Models\StudentDetails; class StudentsImport implements ToModel, SkipsOnFailure, WithValidation, WithHeadingRow { use Importable, SkipsFailures; /** * @param Collection $collection */ public function model(array $row) { return new StudentDetails([ 'roll_no' => $row['roll_no'], 'student_id' => $row['student_id'], 'div' => $row['div'], 'name' => $row['name'], 'gender' => $row['gender'], 'user_key' => session()->get('user_id'), 'group_key' => $group_key ]); } public function onFailure(Failure ...$failures) { // Handle the failures how you'd like. } public function rules(): array { return [ 'student_id' =>[ 'required', 'string', 'unique:student_details' ], 'roll_no' =>[ 'required', 'integer' ], 'name' => [ 'required', 'string', ] ]; } }
My main goal is when a student is inserted into the "student_details" table, insert the student record into all associated tables with the foreign key "student_id". If there is any other way, please help.
instead of using
Maatwebsite\Excel\Concerns\ToModel
You can useMaatwebsite\Excel\Concerns\OnEachRow
. You have more control over what happens on each row.As for making this happen in transactions: