Jaskaran Singh Puri Jaskaran Singh Puri - 1 month ago 7
MySQL Question

Laravel not inserting Auth::id into table

I'm looking to insert multiple column values into a table 'answers'. I'm inserting a question_id from questions table, which is being inserted successfully.

But it's not inserting the auth:user() id now, returning '0' in the table

answercontroller code:

<?php

namespace App\Http\Controllers;

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

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


If I remove the
questions()->findOrFail($question_id)->first()
part, it inserts the auth::id, but not with this, how can I fix it?

Answer

It is because Laravel automatically fills the foreign key when a model is created using related models. Like if I split your query it will look as:

$user = Auth::user();
$question = $user->questions()->findOrFail($question_id)->first();
$question->answers()->create($request->all());

Here answers model is created by $question Model object so it will automatically fills the question_id but will not fill user_id as it is not creates using $user.

But if you write your code as:

$user->answers()->create($request->all());

It will automatically fill the user_id field.

Update

To fill question_id you can write as:

$inputs = $request->all();
$inputs['question_id'] = $question_id;
$user->answers()->create($inputs);
Comments