Laravel 5.2 Entrust transfer error, cannot add foreign key constraints

I installed and configured Laravel 5.2, its working tone, for User ACL I installed the zizaco/entrust during the execution of this php artisan migrate command (to create the roles , permissions table etc.), getting the following error

[Illuminate \ Database \ QueryException] SQLSTATE [HY000]: General Error: 1215 Unable to add foreign key constraint (SQL: change role_user table add foreign key user_id constraint ( user_id ) refers to `` ( id ) to delete the cascade when updating the cascade)

[PDOException] SQLSTATE [HY000]: General Error: 1215 Failed to add foreign key constraint

What could be the reason? Am I missing something? I followed the steps on the principle of "trust the site

+8
laravel entrust
source share
2 answers

I fixed this problem, the name of the users table was missing in the proxy transfer file. see next line

$ table-> foreign ('user_id') β†’ links ('id') β†’ on ( '' ) β†’ onUpdate ('cascade') β†’ onDelete ('cascade');

So, I changed it,

$ table-> foreign ('user_id') β†’ links ('ID') β†’ by (' Users ') β†’ OnUpdate (' Cascade ') β†’ OnDelete (' cascade ");

I added the users table name and the problem is fixed.

The reason why I got this problem?

there was no key / pair 'table'=>'users' in the config/auth.php file, mentioned in the providers array, see below (this default value means that when installing a new laravel)

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

and the php artisan entrust:migration command runs the command, it pulls the users table name from the providers array above, if there is no specified table in the migration file, the relations are set to empty, like this.

$ table-> foreign ('user_id') β†’ links ('ID') β†’ by ( '' ) β†’ OnUpdate ('Cascade') β†’ OnDelete ('cascade');

So, add a table to the providers array like this.

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

after this run command to transfer the php artisan entrust:migration request, this will create the proper migration file.

+17
source share

Sometimes I get the same error when I try to add foreign keys to the same migration (same Schema::create block). If I create a migration when I create a new column:

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

And then in the same file I set this column as a foreign key:

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

It works great.

Hope this helps you.

+1
source share

All Articles