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

mowais's avatar

Add record in Pivot table by sending API request from react - Laravel 5.6

I am trying to creating a record by using laravel eloquent relation ship.

The background is, I have a 3 tables

  1. User 2) Event 3) event_visitors (consider visitor as a user) so when the user will create an event from the react js API, the event and event visitors should add in the table "event_visitors".

To achieve this I am sending an API request from react application along with an array of visitors.

speakers_list: [12, 11]

Migration: event_visitors

    Schema::create('event_visitors', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('event_id')->unsigned();
        $table->integer('visitor_id')->unsigned();
        $table->boolean('is_speaker');
        $table->timestamps();
    });
    Schema::table('event_visitors', function($table) {
        $table->foreign('event_id')->references('id')->on('event')->onDelete('cascade');
        $table->foreign('visitor_id')->references('id')->on('users')->onDelete('cascade');
    });

User.php

public function events(){
    return $this->belongsToMany('App\Events', 'event_visitors');
}

Events.php

public function users(){
    return $this->belongsToMany('App\Events', 'event_visitors');
}

EventsController.php

public function store(Request $request){
    $user = $request->user();

    $user->visitors->user()->detach();
    foreach ($request['user_id'] as $user) {
        $user->tutor->events()->attach([
            $user['speakers_list'] => ['event_id' => $subject['visitor_id']],
        ]);
    }
}

I am struggling a lot, please help

Thanks in advance

0 likes
1 reply
Sinnbeck's avatar

What issue are you having right now? Getting the ids from the request? How to attach relations? Or something else?

Please or to participate in this conversation.