Laravel 7, use of Foreign key

Asked

Viewed 91 times

0

Good morning, I am doing a small project in Laravel 7 and it is the first time that I use Foreign Key and relate two Database tables. In both Models of the respective tables I have already put a list of One To One. When creating a product and saving gives me this error, "General error: 1364 Field 'id_form' doesn’t have a default value", id_form is Foreign key. I have a Database table called form that has an id, then I have a table Question that via fetch the form id.

To develop the application I joined the two database tables in the same Controller, this is what I have in Controller,

public function store(Request $request)
    {
        $request->validate([
            'name_form' =>'required',
            'description' => 'required',
            'email' => 'required',
            'end_date' => 'required',
            //'data_type' => 'required',
            'question' => 'required'
        ]);

        $form = new Forms([
            'name_form' => $request->get('name_form'),
            'description'=> $request->get('description'),
            'email'=> $request->get('email'),
            'end_date' => $request->get('end_date')           
        ]);

        $question = new Questions([
            //'data_type'=> $request->get('data_type'),
            'question'=> $request->get('question')
        ]);

        $form->save();
        $question->save();

        return redirect('/backoffice/forms')->with('success', 'O formulário foi criado com sucesso.');
    }

Can anyone help me to get the table questions to get the form id?

1 answer

0


You’re not passing the "key" id_form for your Questions model it must have its primary key id of the other table as the data passed to that function through the request. Should be:

$question = new Questions([
    //'data_type'=> $request->get('data_type'),
    'question'=> $request->get('question'),
    'id_form' => $id_do_formulario_relacionado_aqui
]);
  • 1

    Thanks for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.