The foreign key is not for Laravel but rather for your database to keep it's integrity.
You must set user_id in your StudentController.
Laravel 5.8 foreign key
I'm trying to connect my tables via foreign key.So I updated my students table as below
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->date('birthday');
$table->string('address');
$table->string('school');
$table->string('student_email');
$table->string('student_mobile');
$table->string('mother_name');
$table->string('mother_mobile');
$table->string('mother_email');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
Then I have updated store function in studentcontroller as below.
$newStudent->name = $request->name;
$newStudent->birthday = $request->birthday;
$newStudent->address = $request->address;
$newStudent->school = $request->school;
$newStudent->student_email = $request->student_email;
$newStudent->student_mobile = $request->student_mobile;
$newStudent->mother_name= $request->mother_name;
$newStudent->mother_mobile = $request->mother_mobile;
$newStudent->mother_email = $request->mother_email;
$newStudent->save();
return redirect()->route('student.index')->withStatus(__('User successfully created.'));
When I try to store data it generate a error saying that SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value . I know that I haven't mentioned ** user_id** at studentcontroller. Also I know that user_id can be added as follow
$newStudent->user_id = Auth::User()->id;
Could anyone please tell me how to use foreign key in laravel for store data. Any how should relevant controller or model to be updated. Please help
Please or to participate in this conversation.