Jaskaran Singh Puri
Jaskaran Singh Puri

Reputation: 739

Laravel how to pass multiple values in query

I'm trying to create a new row in my table using laravel 5.2 queries.

My table "answers" has 5 columns-> answer_id (auto_inc), people_id(sames as Auth::id), question_id('Integer'), answer(input field), created_at(timestamp())

answercontroller file:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use App\Http\Requests;

class answerController extends Controller
{
    public function store(Requests\answerAddRequest $request)
    {
        Auth::user()->questions('question_id')->answers()->create($request->all());
    }
}

answers model class

class answers extends Model
{
    protected $table='answers';
    protected $fillable='answer';
    protected $primaryKey='answer_id';
    public function setUpdatedAtAttribute($value) {}
    public function User()
    {
        return $this->belongsTo('App\User');
    }
    public function questions()
    {
        return $this->belongsTo('App\questions','people_id');
    }
}

I'm unable to add a new row in answers table as I'm not able to understand how can I pass the question_id in the table

questions model class

class questions extends Model
{
    protected $table='questions';
    protected $primaryKey='question_id';
    protected $fillable = [
       'question', 'created_at','details'
    ];
    //protected $hidden=['question_id'];
    public function setUpdatedAtAttribute($value) {}
    public function User() {
        return $this->belongsTo('App\User');
    }
    public function answers()
    {
        return $this->hasMany('App\answers','answer_id');
    }
    public function scopefetchQuestions($query) {
        return $query->select('question','question_id')->where('people_id','=',Auth::id())->get();
    }
}

It's throwing this error with the current code:

BadMethodCallException in Builder.php line 2405:
Call to undefined method Illuminate\Database\Query\Builder::answers()

How can I fix it?

Upvotes: 1

Views: 2224

Answers (1)

Roman
Roman

Reputation: 394

Try this please:

class answerController extends Controller
{
    public function store(Requests\answerAddRequest $request)
    {
        $answer = App\Answer::create($request->all());
        Auth::user()->questions()->where('question_id', $request->get('question_id'))->first()->answers()->save($answer);
    }
}

Also add foreign keys to the $fillable array https://laravel.com/docs/5.2/eloquent#inserting-and-updating-models https://laravel.com/docs/5.2/eloquent-relationships#inserting-related-models

Upvotes: 1

Related Questions