John Davidson

php - Vertical and horizontal reading with Laravel Excel

0 comments
Message:


I am currently using Laravel Excel (Maatwebsite) package for excel installation and reading. In my scenario, I first need to read horizontally to the database and then add the answers to the same question to the database by vertical reading.


So far, I have come to the Question field with the standard horizontal reading process, but in the QuestionAnswer column I need to read the answers of the question downwards.


How can I do that?
https://i.stack.imgur.com/yl1k9.png


Here is my save process but I don't know how to get Question Answer column.



public function collection(Collection $rows)
{
foreach ($rows as $row) {
$IDnumber = $row['IDnumber'];
$name = $row['firstname'];
$exam = $row['exam'];
$course = $row['course'];
$courseCode = $row['coursecode'];
$question = $row['question'];

$user = User::withTrashed()->firstOrCreate(
['IDnumber' => $IDnumber],
[
'IDnumber' => $IDnumber,
'first_name' => $firstname,
]
);

$q_insert = \Modules\Qulak\Entities\Question::create(
[
'question' => $question,
'question_type' => 'MCQ',
'user_id' => $user->id,
'created_by' => Auth::user()->id,
'updated_by' => Auth::user()->id,
]
);
}


My Answer:
> In order to read the answers of the question downwards and save them to the database, you can modify your `collection` method as follows:

php
public function collection(Collection $rows)
{
foreach ($rows as $row) {
$IDnumber = $row['IDnumber'];
$name = $row['firstname'];
$exam = $row['exam'];
$course = $row['course'];
$courseCode = $row['coursecode'];
$question = $row['question'];

// Get the question answers by looping through the remaining columns
$answers = [];
foreach ($row as $key => $value) {
if ($key !== 'IDnumber' && $key !== 'firstname' && $key !== 'exam' && $key !== 'course' && $key !== 'coursecode' && $key !== 'question') {
$answers[] = $value;
}
}

// Save the question and answers to the database
$newQuestion = Question::create([
'IDnumber' => $IDnumber,
'name' => $name,
'exam' => $exam,
'course' => $course,
'courseCode' => $courseCode,
'question' => $question,
]);

foreach ($answers as $answer) {
QuestionAnswer::create([
'question_id' => $newQuestion->id,
'answer' => $answer,
]);
}
}
}


This code snippet will loop through each row in the Excel file, extract the question and answers, and save them to the database accordingly. Make sure to adjust the model names and relationships based on your Laravel project structure.

Rate this post

4 of 5 based on 9142 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us