Jaskaran Singh Puri Jaskaran Singh Puri - 5 months ago 32
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:


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)

If I remove the
part, it inserts the auth::id, but not with this, how can I fix it?


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();

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:


It will automatically fill the user_id field.


To fill question_id you can write as:

$inputs = $request->all();
$inputs['question_id'] = $question_id;