Search code examples
phplaravellaravel-artisan

Laravel migration: pivot table role_user doesn't exist


Using Laravel 5, I am making a new project with a n:n relationship between User and Role.

When I empty my database and type the command: php artisan migrate:install (which works) followed by: php artisan migrate, I get the following errors:

[Illuminate\Database\QueryException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'manon.role_user' doesn't exist
(SQL: alter table `role_user` add `user_id` int not null, add `role_id` int not null)

[PDOException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'manon.role_user' doesn't exist

I was inspired by this tutorial.

Here are some simple bits of code:

In Role.php:

public function users()
{
    return $this->belongsToMany('User');
}

In User.php:

public function roles()
{
    return $this->belongsToMany('Role');
}

roles migration:

class CreateRolesTable extends Migration
{
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
        });
    }

    public function down()
    {
        Schema::dropIfExists('roles');
    }
}

role_user migration:

class CreateRoleUserTable extends Migration
{
    public function up()
    {
        Schema::table('role_user', function (Blueprint $table) {
            $table->integer('user_id');
            $table->integer('role_id');
        });
    }

    public function down()
    {
        Schema::dropIfExists('role_user');
    }
}

users migration:

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('firstName');
            $table->string('lastName');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Solution

  • Schema::table('role_user', function (Blueprint $table) {
    

    should be

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

    Note the change: table has changed to create as you are creating this table, not altering it, you cannot alter something which does not exist :)

    The migration is also called CreateRoleUserTable, so indicates it's a creation not an alteration.