0
votes

SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value

why i got that error? and how to fix it?

here's my controlller looks like

    public function create(Request $request, Question $question)
    {

        $data = request()->validate([
            'standart_id' => 'required',
            'question.*.question' => 'required',
            'question.*.question_id' => 'required',
            'user_id' => 'required',
            'question.*.answer' => 'required',
            'files_link' => 'required',
            'description' => 'required',
        ]);

        $data['user_id'] = Auth()->id();

//        dd($data);
//        dd($request->input('question.*.standart_id'));

        $responses = $question->responses()->createMany($data['question']);

    }

here is what i got on diedump $data

array:5 [▼
  "standart_id" => "2"
  "user_id" => 3
  "files_link" => "http://127.0.0.1:8000/auditee/1/respons/"
  "description" => "asdasd"
  "question" => array:3 [▼
    0 => array:3 [▼
      "question" => "test"
      "question_id" => "4"
      "answer" => "Ya"
    ]
    1 => array:3 [▶]
    2 => array:3 [▶]
  ]
]

Can somebody help me with this problem?

EDITED

route for create

Route::post('/standart/{question}/answer/post', [App\Http\Controllers\ResponsController::class, 'create']);

response model

    protected $guarded = [];

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

    public function standart()
    {
        return $this->belongsTo(Standart::class);
    }

question model

    public function standard()
    {
        return $this->belongsTo(Standart::class);
    }

    public function responses()
    {
        return $this->hasMany(Response::class);
    }

standart model

    protected $guarded = [];

    public function questions()
    {
        return $this->hasMany(Question::class);
    }

    public function responses()
    {
        return $this->hasMany(Response::class);
    }
1

1 Answers

0
votes

As error says you are not passing user_id .

$result=collect($request->question)->map(function ($item)use($request) {
  $item['user_id'] = $request->user_id;
  $item['standart_id'] = $request->standart_id;
  $item['files_link'] = $request->files_link;
  $item['description'] = $request->description;
  return $item;
});


Response::insert($result->toArray());