Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nipun's avatar
Level 2

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

0 likes
4 replies
Tray2's avatar

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.

bekaskaki's avatar

for example :

 public function store(Request $request)
    {
          $this->validate($request,[
            'test' => 'integer|min:1',
          
        ]);

       $input = $request->all();
       $input['user_id'] = Auth::user()->id;

Test::create($input);
    Alert::success('Success');
      }else{
            Alert::error('Error');

      }
    
        return Redirect::to('admin/'.$this->title);
    }
Snapey's avatar

even if it were automatic, how would it know which user to pick

Snapey's avatar

your user_id also needs to be bigInteger

Please or to participate in this conversation.