3

I read this https://laravel.com/docs/5.4/eloquent-relationships#many-to-many and I found out that

php artisan migrate

doesn't create the pivot table automatically, I checked how should I create it but I couldn't find out how to create it with extra columns. for example , these are my related models :

class User extends Authenticatable {
  public function courses() 
  {
    return $this->belongsToMany('App\Course')
    ->withPivot('attendance', 'grade');
      ->withTimestamps();
  }
}

the other model

class Course extends Model
{
//
}

which I didn't need an inverse relation to instantiate here.

The issue is when I go to mysql I can't find the pivot table. So how do I create it manually with those pivot columns.

mahmoud fathy
  • 361
  • 1
  • 7
  • 17
  • Create a migration. Basic migration rules are here https://laravel.com/docs/5.4/migrations – u_mulder Aug 19 '17 at 17:23
  • Possible duplicate of [How is a pivot table created by laravel](https://stackoverflow.com/questions/15821822/how-is-a-pivot-table-created-by-laravel) – Bharat Geleda Aug 19 '17 at 17:44
  • @Bharat Geleda I read this thread before I post the question. I needed to specify extra columns which isn't mentioned in the question. Despite his second answer might work with me. But I didn't look at it from this angle. I will try it when I am back. – mahmoud fathy Aug 19 '17 at 19:32
  • Yes none of the documentation about adding an extra column in a pivot table mention about adding the attribute in a migration file. It is implicitly assumed however. Any major changes in database are performed using the migration file alone. The Eloquent ORM model is at a higher level. – Deepak Daniel Apr 12 '19 at 10:16

1 Answers1

5

You have to create the intermediate/pivot table manually (You have to name your table on alphabetical order) using a migration like this:

    public function up()
    {
        Schema::create('course_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
            $table->integer('course_id')->unsigned();
            $table->foreign('course_id')->references('id')->on('courses');
            $table->string('attendance');
            $table->string('grade');
            $table->timestamps();
        });
    }

After this, run migration:

php artisan migrate
Diego Blaker
  • 341
  • 1
  • 7