Ad

Creating A Joined Table With Laravel

- 1 answer

I am using Laravel 6. I want to create a joined table named meeting_user that should connect the tables meetings and users. That's considering that a user could participate to many meetings and a meeting could have many users.

users:

Schema::create('users', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->string('surname');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('username')->unique();
    $table->string('password');
    $table->enum('permission', array(0, 1, 2));
    $table->enum('is_active', array(0, 1))->default(1);
    $table->rememberToken();
    $table->timestamps();
});

meetings:

Schema::create('meetings', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->text('description');
    $table->string('id_room');
    $table->date('date');
    $table->time('start_hour');
    $table->time('end_hour');
    $table->enum('is_active', array(0, 1))->default(1);;
    $table->timestamps();
    $table->foreign('id_room')->references('id')->on('rooms');
});

I would like to create this table with a migration and furthermore I would like that when a user creates a meeting with many users and so inserts a new row to the "meetings" table, even the new "meeting_user" table be dynamically filled in adding new rows. Is there a way to do that with Laravel?

Ad

Answer

you have to create a third table called for example "user_meetings" and it's migration will be

$table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('meeting_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')- 
    >onDelete('cascade');
            $table->foreign('meeting_id')->references('id')->on('meetings')- 
    >onDelete('cascade');

and then put the relation in "user" model

   public function meetings()
    {
        return $this->belongsToMany(Meeting::class, 'user_meetings', 'user_id', 'meeting_id');
    }

and the relation in "meeting" model

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

and the code of "adding" meetings in the controller will be

 $user->meetings()->attach($request->meetings);
        return redirect()->back()->with('success', 'successfull');

and "edit"

   $checker->meetings()->sync($request->meetings);
                return redirect()->back()->with('success', 'successfull');

and "delete"

$checker->meetings()->detach();

i hope these steps will help you

Ad
source: stackoverflow.com
Ad