Support the ongoing development of Laravel.io →
Database Architecture Laravel
Last updated 2 years ago.
0

Hello Alex,

In my database "questions" stands: "question_id", "body", "answer1", "answer2", "answer3"

Answers should be stored in a different table, with a different Eloquent Model. This way, you can create a relationship between Question and Answers. More specifically a one to many (one question can have many answers).

This is easy to do with Laravel, you should take a look here: https://laravel.com/docs/5.4/eloquent-relationships#one-to-many

Or here: https://laracasts.com/series/laravel-from-scratch-2017/episodes/7

Basically, you will need 2 models:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Question extends Model
{
    public function answers()
    {
        return $this->hasMany(Answer::class);
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Answer extends Model
{
    public function question()
    {
        return $this->belongsTo(Question::class);
    }
}

Then, from the $question object:

$question = Question::first();
foreach($question->answers as $answer){
   //here you have access to all answers
}

Good luck!

Last updated 7 years ago.
0

Hello Igor, thank you for your answer!

I did it this way:

@foreach ($questions as $question)
<button>{{ $question->body }} </button>
<a href="answers/{{ $question->id }}">Get Answers</a>
@endforeach
Route::post('answers/{id}', 'QuestionController@getAnswers')
public function getAnswers($id)
{
 $question= Question::findorFail($id);
 return view('question', ['question' => $question]);
 }
<p>{{ $question->answer1 }}</p>
<p>{{ $question->answer2 }}</p>
<p>{{ $question->answer3 }}</p>

Now I want to check if the user already answered a question and if the answer was correct. I will make a new post for that, thanks and regards

rogo

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Alex Alex rogo Joined 5 Jul 2017

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.