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

mvww11's avatar

Instance belongsTo many

Hello!

I'm writing a small tutoring center app for organizing all its lectures.

I have 3 classes: Lectures, Teacher and Student. I want a Lecture to belong to a teacher and a student as well.

The Teacher and the Student are already stored on the database. I'm having a hard time storing a new Lecture while assigning it a Teacher and a Student.

On the migration:

Schema::create('lectures', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('student_id');
            $table->integer('teacher_id');
            $table->timestamps();
        });

The form for creating the lecture:

<form method="POST" action="/aulas">

            {{ csrf_field() }}

            
            <div class="form-group">
              <label for="name">Nome da Aula:</label>
              <input type="text" class="form-control" id="name" name="name" required>
            </div>

            <div class="form-group">
              <label for="student">Aluno</label>
              <input type="text" class="form-control" id="student" name="student" required>
            </div>

            <div class="form-group">
              <label for="teacher">Professor</label>
              <input type="text" class="form-control" id="teacher" name="teacher" required>
            </div>


            <div class="form-group">
              <button type="submit" class="btn btn-primary">Criar</button>
            </div>
          
        </form>

The action calls LecturesController@store. My problem is, using the form above, how can I call App\Teacher::where('name', 'request('teacher'))->pluck('id'); and pass it to the teacher_id for this new Lecture instance, as well as calling App\Student::where('name', 'request('student'))->pluck('id'); and pass it to the teacher_id for this new Lecture instance.

Thanks in advance!

0 likes
1 reply
Borisu's avatar
Borisu
Best Answer
Level 37

Well you should use a dynamically set select tag which already gets the id's of the teacher and the student...

If you insist on your way you can do this:

$teacher_id = App\Teacher::where('name', request('teacher'))->first()->id
$student_id = App\Student::where('name', request('student'))->first()->id
1 like

Please or to participate in this conversation.