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

unkown.persone's avatar

Add columns to pivot table in Laravel

I have 4 Models:

Student Tutor Course Admin

I am able to fetch all the students and tutors with their Ids. I want to the admin to create Courses and store them in pivot Tables:

course_student course_tutor

Yet, the relationships are not too clear for me. I assume that I need belongsToMany between Course and Student. The same goes for Tutor and Course am i right?

What is also not clear is, how can I select many values on the HTML side and submit them to the server.

E.g:

public function store(AdminCreateNewCourseRequest $request)
{
    $this->authorize('create-course');

    $course = new Course;

    $course->name               = $request->name;
    $course->tutor_id           = $request->tutor_id;
    $course->student_id         = $request->student_id;
    $course->spoken_language    = $request->spoken_language;
    $course->description        = $request->description;

    $course->save();

    What to do?

    return redirect($course->path())
        ->with('flash', 'The course has been published');
}

Here is the AdminCreateNewCourseRequest

public function rules()
{
    return [
        'name'          =>  'required|unique:courses|max:60',
        'tutor_id'      =>  [
            'required',
                            Rule::exists('tutors', 'id');
        ],
        'student_id'      =>  [
            'required',
            Rule::exists('students', 'id');
        ],
        'spoken_language'    =>  'required',
        'description'   =>  'required|max:255'
    ];
}

I might let the admin selects multiple tutors and students.

How can I accomplish this?

Many Thanks.

0 likes
0 replies

Please or to participate in this conversation.