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.

4
  • Create a migration. Basic migration rules are here laravel.com/docs/5.4/migrations Commented Aug 19, 2017 at 17:23
  • Possible duplicate of How is a pivot table created by laravel Commented Aug 19, 2017 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. Commented Aug 19, 2017 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. Commented Apr 12, 2019 at 10:16

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.