Laravel 5.2 Entrust migrate error, cannot add foreign key constraints

I fixed the issue, in entrust migration file, there was users table name missing. see following line

$table->foreign('user_id')->references('id')->on(' ')->onUpdate('cascade')->onDelete('cascade');

So I changed to this,

$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');

I added the users table name, and issue is fixed.

Reason, Why I got this issue?

in config/auth.php file, there was not a 'table'=>'users' key/pair mentioned in providers array, see below (this is default, means when fresh laravel is installed)

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

while php artisan entrust:migration command runs, it pulls the users table name from above providers array, if there is no table mentioned then in migration file, relationship sets empty like this.

$table->foreign('user_id')->references('id')->on('')->onUpdate('cascade')->onDelete('cascade');

So, add table in provider array like this.

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
        'table'=>'users'
    ],

after that run command for entrust migration php artisan entrust:migration this will generate the proper migration file.


I get same error sometimes when I'm trying to add foreign keys in the same migration (same Schema::create block). If I'm creating migration where I'm creating new column:

Schema::create(...
    ...
    $table->integer('categories_id')->unsigned();
    ...
});

And then in the same file I'm setting this column as foreign key:

Schema::table('sub_categories', function (Blueprint $table) {
    $table->foreign('categories_id')->references('id')->on('main_categories');
});

It works perfectly.

Hope this will help you.