Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 Entrust migrate error, cannot add foreign key constraints

I installed and configure the Laravel 5.2, its working fine, for User ACL I installed the zizaco/entrust package while running this command php artisan migrate (for creating roles, permissions table etc) getting following error

[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table role_user add constraint role_user_user_id_foreign foreign key (user_id) references `` (id) on delete cascade on update cascade)

[PDOException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

What could be the reason ? am I missing something ? I followed the step wise guideline from entrust site

like image 577
Qazi Avatar asked Mar 12 '16 10:03

Qazi


1 Answers

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.

like image 80
Qazi Avatar answered Oct 22 '22 04:10

Qazi