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

St24's avatar
Level 1

How to post data to two tables using one form ?

How do I post in two tables using one form in Laravel?

I have two tables, students and parents, I created the models and linked them. I created the controllers for both tables as well.

I have a ‘create student’ form where I accept student name and parent name but I want to send students name to students table and parents name to parents table which is joined by the student_id field. Any idea how I can achieve this ?

0 likes
3 replies
tykus's avatar

You create a Student instance from the student form inputs, then using that instance, through the relationship, create a Parent instance using the parent inputs:

// StudentController

public function store(Request $request)
{
	$student = Student::create($request->input('student'));

	$student->parent()->create($request->input('parent'));
}

You can group the student and parent inputs in your form, for example:

<input type="text" name="student[first_name]" />
<input type="text" name="student[last_name]" />

<input type="text" name="parent[first_name]" />
<input type="text" name="parent[last_name]" />
Lara_Love's avatar

@tykus Hello i read it and very try for solve it but how store in Controller ~~ $input['user_id'] = auth()->user()->id; ~~ my form

<form method="post" action="{{ route('reply.store') }}">
              @csrf
                        <textarea id="editor" class="form-control" name="body"></textarea>
                      <input type="hidden" name="ticket_id" value="{{ $post->id }}"/>
                      <input type="hidden" name="close" value="1"/>
                 <x-BtnSend/>
</form>

send to store

public function store(Request $request)
    {
        $request->validate([
            'body'=>'required',
        ]);
        $input = $request->all();
        $input['user_id'] = auth()->user()->id;
        Ticket::where('id',$request->id)->update(['close'=>'1']); --> database Ticket
        Replies::create($input);--> database Reply
      return redirect()->back()->with('success',

any ticket has Many reply

w99910's avatar

in App\Models\Student.php

public function parents(){
   return $this->hasMany(Parent::class);
}

save data

$parent = Parent::create(['name'=>$request->parent_name]);
$student = Student::create(['name'=>$request->student_name]);
$student->parents()->save($parent);

https://laravel.com/docs/8.x/eloquent-relationships#one-to-many

I might be wrong in using one to many relationship.

Please or to participate in this conversation.