Level 102
What issue are you having right now? Getting the ids from the request? How to attach relations? Or something else?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I am trying to creating a record by using laravel eloquent relation ship.
The background is, I have a 3 tables
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
Please or to participate in this conversation.