-2

i'm creating a simple question-and-answer web app using Laravel, and i'm new to this,

So there's a USER who posts a QUESTION and letting someone to ANSWER the question, my progress so far, I can register as a USER, post a QUESTION, BUT i'm having trouble saving the ANSWER, here's my code:

{!! Form::open(['action' => 'AnswersController@store', 'method' => 'POST'])!!}
 <div class="from-group">
 {{Form::label('answer', 'Answer')}}
 {{Form::textarea('answer', '', ['class' => 'form-control', 'placeholder' => 'type your answer here'])}} 
  <br>
 {{Form::submit('Submit Answer', ['class' => 'btn btn-primary'])}} 
 </div> 
{!! Form::close()!!} 

and here's a Screenshot of it:
UI Screenshot

Now i want to insert the answer to my database, the table structure is: database table structure

and here is my Store function from my controller:

public function store(Request $request)
    {
        $this->validate($request, [
            'answer' => 'required'
        ]); 
            $answer = new Answer;
            $answer->answer = $request->input('answer'); 
            $answer->question_id = $question_id;
            $answer->user_id = auth()->user()->id;
            $answer->save();

        return redirect('/answer/$question_id')->with('success', 'Answer Posted');
    }

Now, My biggest problem is, how can I get the question ID? Every time I run this, it's giving me errors:

Trying to get property of non-object

And i think its referring to the "question_id"

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
Yeoj
  • 1
  • can you share web.php code? – Ahmed Atoui Oct 04 '19 at 14:41
  • 1
    you have to set `question_id` in request. via hidden form input, for example. or better via parameter in your route – Roman Meyer Oct 04 '19 at 14:46
  • *"Trying to get property of non-object"* would not refer to `$question_id`, as you're not trying to get a property of it (`->` denotes object access, like `$object->property`). That error should tell you what line this is occurring on, but I suspect it's `auth()->user()->id`. Are you logged in? Is this route wrapped in `auth` middleware? – Tim Lewis Oct 04 '19 at 15:07

1 Answers1

0

There is undefined $question_id in your code. You have to transfer your question ID into your request.

The simplest (but not the best) way is adding hidden input with $question->id into form:

{{ Form::hidden('question_id', $question->id) }}

And then in controller you have to get ID from request:

 $answer->question_id = $request->get('question_id');

P.S. Note that Form helpers are deprecated since Laravel 5.x So you should use usual HTML markup for that.

Roman Meyer
  • 2,634
  • 2
  • 20
  • 27