php – Laravel 5.6 Attach Multiple Users (Speakers) with the Event-ThrowExceptions

Exception or error:

I am trying to attach Users list to the events by sending an array of IDs of the users, I have the following table structure in Laravel.

Events (table)

Schema::create('events', function (Blueprint $table) {

        Schema::table('events', function($table) {

Event Users (table)

Schema::create('event_user', function (Blueprint $table) {
    Schema::table('event_user', function($table) {

Events Controller (Store method)

        $events = new Events;

        $events->organiser_id = $request->user()->id;

        $speakers = User::find($request->user()->id);
        $speakers->events()->attach($request->speakers_list, ['is_speaker' => true]);

Event (Model)

public function users(){
        return $this->belongsToMany(User::class, 'users');

User (Model)

public function events(){
        return $this->belongsToMany(Events::class, 'event_user', 'event_id', 'user_id')->withTimestamps();

when I am trying to attach users with the event, I am getting the following error

message: “SQLSTATE[23000]: Integrity constraint violation:

1452 Cannot add or update a child row: a foreign key constraint fails (acp_db.event_user, CONSTRAINT event_user_event_id_foreign FOREIGN KEY (event_id) REFERENCES events (id) ON DELETE CASCADE ON UPDATE CASCADE)

(SQL: insert into event_user (created_at, event_id, is_speaker, updated_at, user_id) values (2020-03-15 19:49:49, 11, 1, 2020-03-15 19:49:49, 12), (2020-03-15 19:49:49, 11, 1, 2020-03-15 19:49:49, 13))”

How to solve:

You are providing a table name of users to the Event::users() many-to-many relationship. Since you are using proper naming conventions, you don’t need any parameters to either relationship definition:

class Event extends Model
    public function users() {
        return $this->belongsToMany(User::class);
class User extends Model
    public function events() {
        return $this->belongsToMany(Event::class);

Leave a Reply

Your email address will not be published. Required fields are marked *