Support the ongoing development of Laravel.io →
Database Eloquent

I have defined the following two Models:

Question.php:

<?php

class Question extends \Eloquent
{
    protected $table = 'questions';
    protected $guarded = ['id'];

    public function answers()

    {

        return $this->hasMany('Answer');

    }
}

Answer.php:

<?php

class Answer extends \Eloquent
{
    protected $table = 'answers';
    protected $guarded = ['id'];

    public function question()
    {
        return $this->belongsTo('Question');
    }
}

And I'm trying to insert data to the Pivot table using this:

$answer = Answer::create([
                        'answer' => $value,
                        'question_id' => $question->id,
                    ]);

$question = Question::find($question->id);
$question->answers()->attach($answer->id);

But I'm getting error that function attach() is undefined. How to solve this?

Last updated 3 years ago.
0
Solution

There is no pivot table as this is a 1-N relationship. Just use

$question->answers()->save($answer);

To insert an answer related to a question.

Last updated 3 years ago.
0

Thanks. Then $answer will have only the following:

$answer = [
                        'answer' => $value,
                    ];

Right?

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

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.

© 2025 Laravel.io - All rights reserved.