Laravel 8 General error: 1215 Cannot add foreign key constraint - laravel

I get this error when i want to create teble from artisan tool.
Migrating: 2022_06_06_114027_create_subjekat_adrese_table
Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `subjekat_adrese` add constraint `subjekat_adrese_subjekti_id_foreign` foreign key (`subjekti_id`) references `subjekti` (`id`) on delete cascade)
at vendor/laravel/framework/src/Illuminate/Database/Connection.php:712
708▕ // If an exception occurs when attempting to run a query, we'll format the error
709▕ // message to include the bindings with SQL, which will make this exception a
710▕ // lot more helpful to the developer instead of just the database's errors.
711▕ catch (Exception $e) {
➜ 712▕ throw new QueryException(
713▕ $query, $this->prepareBindings($bindings), $e
714▕ );
715▕ }
716▕ }
+9 vendor frames
10 database/migrations/2022_06_06_114027_create_subjekat_adrese_table.php:37
Illuminate\Support\Facades\Facade::__callStatic("create")
+22 vendor frames
33 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
What i try:
public function up()
{
Schema::create('subjekat_adrese', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('naziv');
$table->string('adresa');
$table->boolean('primarna')->unique();
$table->bigInteger('subjekti_id')->index();
$table->bigInteger('drzave_id')->index();
$table->bigInteger('gradovi_id')->index();
$table->bigInteger('poste_id')->index();
$table->timestamps();
$table->foreign('subjekti_id')->references('id')->on('subjekti')->onDelete('cascade');
$table->foreign('drzave_id')->references('id')->on('drzave')->onDelete('SET NULL');
$table->foreign('gradovi_id')->references('id')->on('gradovi')->onDelete('SET NULL');
$table->foreign('poste_id')->references('id')->on('poste')->onDelete('SET NULL');
});
Try 2
public function up()
{
Schema::create('subjekat_adrese', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('naziv');
$table->string('adresa');
$table->boolean('primarna')->unique();
$table->bigInteger('subjekti_id')->index();
$table->bigInteger('drzave_id')->index();
$table->bigInteger('gradovi_id')->index();
$table->bigInteger('poste_id')->index();
$table->timestamps();
});
Schema::table('subjekat_adrese', function($table) {
$table->foreign('subjekti_id')->references('id')->on('subjekti')->onDelete('cascade');
$table->foreign('drzave_id')->references('id')->on('drzave')->onDelete('SET NULL');
$table->foreign('gradovi_id')->references('id')->on('gradovi')->onDelete('SET NULL');
$table->foreign('poste_id')->references('id')->on('poste')->onDelete('SET NULL');
});
}
I dont know what to try next but nothing not wotk.

$table->foreignId('user_id')->constrained()->onDelete('cascade');
you tried it in this way to see ??
I mean this way instead of
$table->foreign('subjekti_id')->references('id')->on('subjekti')->onDelete('cascade');

Related

Laravel migration: integrity constraint violation

I get an error whenever I try to insert values into this table.
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(usersexam.role_user, CONSTRAINT role_user_role_id_foreign
FOREIGN KEY (role_id) REFERENCES roles (id) ON DELETE CASCADE)
Here is the migration for that table in my Laravel's database folder:
class CreateRoleUserPivotTable extends Migration
{
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->foreignId('role_id')->references('id')->on('roles')
->cascadeOnDelete();
$table->foreignId('user_id')->references('id')->on('users')
->cascadeOnDelete();
});
}
public function down()
{
Schema::dropIfExists('role_user');
}
}
So I am inserting it into two columns. What is wrong with the table?
UPDATE: here is my insert query
when ever ur creating a tables and refrense a foreign key u still need to make the columns so instead of
Schema::create('role_user', function (Blueprint $table) {
$table->foreignId('role_id')->references('id')->on('roles')->cascadeOnDelete();
$table->foreignId('user_id')->references('id')->on('users')->cascadeOnDelete();
});
it should be something like
Schema::create('role_user', function (Blueprint $table) {
$table->unsignedInteger('role_id');
$table->unsignedInteger('user_id');
$table->foreign('role_id')
->references('id')
->on('roles')
->cascadeOnDelete();
$table->foreign('user_id')
->references('id')
->on('users')
->cascadeOnDelete();
});

Laravel: Migration & Seeding Problems

I am trying to seed a database and am getting an error when I run php artisan migrate:fresh:
Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `news` add constraint `news_author_id_foreign` foreign key (`author_id`) references `authors` (`id`) on delete cascade)
at C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:669
665| // If an exception occurs when attempting to run a query, we'll format the error
666| // message to include the bindings with SQL, which will make this exception a
667| // lot more helpful to the developer instead of just the database's errors.
668| catch (Exception $e) {
> 669| throw new QueryException(
670| $query, $this->prepareBindings($bindings), $e
671| );
672| }
673|
1 C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")
2 C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
PDOStatement::execute()
Here are the migration files:
Schema::create('news', function (Blueprint $table) {
$table->bigIncrements('id');
...
$table->unsignedBigInteger('author_id');
$table->foreign('author_id')
->references('id')
->on('authors')
->onDelete('cascade');
});
Schema::create('authors', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
And here are the factory files:
$factory->define(Author::class, function (Faker $faker) {
return [
'name' => $faker->name
];
});
return [
...
'author_id' => $faker->numberBetween($min = 1, $max = 50),
];
And finally, here are the seed files:
// DatabaseSeeder
{
$this->call(AuthorsTableSeeder::class);
$this->call(NewsTableSeeder::class);
}
// NewsSeeder and AuthorSeeder
factory(App\News::class, 150)->create();
factory(App\Authors::class, 50)->create();
Any idea why I am getting this error and what I can do to fix it?
Thanks.
simply because the migration file for news runs before authors
just try to change the timestamp for these two files to make authors migration run before news migration

Foreign key constraint is incorrectly formed in laravel 7

I am building a hotel management application using laravel. I am trying to create the tables 'reservations' in laravel but when I run the 'migrate:fresh' command, I get the following: error "Foreign key constraint is incorrectly formed". Can anyone tell what do you mean by this error?
View Error
public function up()
{
Schema::create('room_types', function (Blueprint $table) {
$table->id();
$table->string('title')->unique();
$table->string('slug')->unique();
$table->string('short_code')->unique();
$table->longText('description')->nullable();
$table->integer('base_capacity')->default(0);
$table->integer('higher_capacity')->default(0);
$table->boolean('extra_bed')->default(0);
$table->integer('kids_capacity')->default(0);
$table->float('base_price',8,2)->default(0);
$table->float('additional_person_price',8,2)->default(0);
$table->float('extra_bed_price',8,2)->default(0);
$table->boolean('status')->default(1);
$table->softDeletes();
$table->timestamps();
});
}
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('usertype')->default('user');
$table->string('last_name')->nullable();
$table->string('phone')->nullable();
$table->date('dob')->nullable();
$table->longText('address')->nullable();
$table->enum('sex',['M','F','O'])->default('M');
$table->string('picture')->nullable();
$table->string('id_type')->nullable();
$table->string('id_number')->nullable();
$table->string('id_card_image_front')->nullable();
$table->string('id_card_image_back')->nullable();
$table->string('company_name')->nullable();
$table->string('gst_no')->nullable();
$table->text('remarks')->nullable();
$table->boolean('vip')->default(0);
$table->boolean('status')->default(1);
$table->rememberToken();
$table->timestamps();
});
}
public function up()
{
Schema::create('reservations', function (Blueprint $table) {
$table->id();
$table->integer('uid')->unique();
$table->timestamp('date');
$table->unsignedInteger('user_id');
$table->unsignedInteger('room_type_id');
$table->integer('adults')->default(1);
$table->integer('kids')->default(0);
$table->date('check_in');
$table->date('check_out');
$table->integer('number_of_room')->default(1);
$table->enum('status',['PENDING','CANCEL','SUCCESS'])->default('PENDING');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('room_type_id')->references('id')->on('room_types')->onDelete('cascade');
});
}
Error message
SQLSTATE[HY000]: General error: 1005 Can't create table `hotelplex`.`reservations` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `reservations` add constraint `reservations_reservations_user_id_foreign` foreign key (`reservations_user_id`) references `users` (`id`) on delete cascade)
at C:\xampp\htdocs\hotelplex\vendor\laravel\framework\src\Illuminate\Database\Connection.php:669
665| // If an exception occurs when attempting to run a query, we'll format the error
666| // message to include the bindings with SQL, which will make this exception a
667| // lot more helpful to the developer instead of just the database's errors.
668| catch (Exception $e) {
> 669| throw new QueryException(
670| $query, $this->prepareBindings($bindings), $e
671| );
672| }
673|
1 C:\xampp\htdocs\hotelplex\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `hotelplex`.`reservations` (errno: 150 "Foreign key constraint is incorrectly formed")")
2 C:\xampp\htdocs\hotelplex\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
PDOStatement::execute()
Laravel6
Laravel6 does not have any method id() to create id in a table. Laravel7 does.. I tried creating id using $table->id() using Laravel6 and got the below error.
It seems you posted wrong error or you have already created id manually in your tables.
You can use bigIncrements,bigInteger, increments,integer etc.
You can find all available methods here
Laravel7
As per Laravel7 $table->id() is alias of Alias of $table->bigIncrements('id') i.e. unsigned big integer.
To create Foreign key the data type for the child column must match the parent column exactly.
Since users.id and room_types.id is a bigIncrements then reservations.user_id and reservations.room_type_id also needs to be an unsignedbigInteger, not a unsignedInteger.
So to make it work
change
$table->unsignedInteger('user_id');
$table->unsignedInteger('room_type_id');
to
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('room_type_id');
Like this:
public function up()
{
Schema::create('reservations', function (Blueprint $table) {
$table->id();
$table->integer('uid')->unique();
$table->timestamp('date');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('room_type_id');
$table->integer('adults')->default(1);
$table->integer('kids')->default(0);
$table->date('check_in');
$table->date('check_out');
$table->integer('number_of_room')->default(1);
$table->enum('status',['PENDING','CANCEL','SUCCESS'])->default('PENDING');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('room_type_id')->references('id')->on('room_types')->onDelete('cascade');
});
}
https://laravel.com/docs/7.x/migrations#creating-columns
The problem seems to be of data type mismatching for user_id and room_type_id
$table->id(); alias of Alias of $table->bigIncrements('id');
https://laravel.com/docs/master/migrations#columns
So, you need foreign user_id and room_type_id column on reservations like:
public function up()
{
Schema::create('reservations', function (Blueprint $table) {
// Structure
$table->id();
...
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('room_type_id');
...
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('room_type_id')->references('id')->on('room_types')->onDelete('cascade');
...
})
}
on laravel 8, you can use this
$table->id();
....
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('room_type_id');
...
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('restrict');
$table->foreign('room_type_id')->references('id')->on('room_types')->onDelete('restrict');
The ->onDelete('cascade'); should be on the relationships creation part.
Change the to:
public function up()
{
Schema::create('reservations', function (Blueprint $table) {
// Structure
$table->id();
$table->integer('uid')->unique();
$table->timestamp('date');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('room_type_id');
$table->integer('adults')->default(1);
$table->integer('kids')->default(0);
$table->date('check_in');
$table->date('check_out');
$table->integer('number_of_room')->default(1);
$table->enum('status',['PENDING','CANCEL','SUCCESS'])->default('PENDING');
$table->timestamps();
// Relationships
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('room_type_id')->references('id')->on('room_types')->onDelete('cascade');
});
}

errno: 150 "Foreign key constraint is incorrectly formed" in Laravel

Schema::create('position', function (Blueprint $table) {
$table->increments('post_id');
$table->String('post_name');
$table->timestamps();
});
Schema::create('candidate', function (Blueprint $table) {
$table->increments('id');
$table->String('name');
$table->String('branch');
$table->unsignedInteger('post_id');
// $table->foreign('post_id_no')->references('post_id')->on('position')->onDelete('cascade');
$table->foreign('post_id')->references('post_id')->on('position')->onDelete('cascade');
$table->integer('count')->default(0);
$table->timestamps();
});
I have two tables, position and candidate. When I migrate I get error for foreign key. can anyone say whats error in code?
This is error I get when I migrate:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table voting.#sql-16b7_2b (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table candidate add constraint candidate_post_id_foreign foreign key (post_id) references position (post_id) on delete cascade)
catch (Exception $e) {
throw new QueryException(
$query, $this->prepareBindings($bindings), $e
);
}
PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `voting`.`#sql-16b7_2b` (errno: 150 "Foreign key constraint is incorrectly formed")")
Likely a mismatch on the foreign key column and the referencing column possibly not being the same type or length. Instead of
$table->unsignedInteger('post_id');
in your candidate table, try:
$table->integer('post_id')->unsigned()->index();
Also, it is sometimes helpful and more clear (perhaps to mysql) to keep the original (position) id as just 'id'. You can call it post_id in the candidate table and reference 'id' on position. A little easier to understand.
You need to specify your default-engine as
$table->engine = 'InnoDB';
And make sure you have created the position table which the table candidate is referencing to. Please add your voting table schema in the post too.
You can try this.
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('post_id')->on('position')->onDelete('cascade');
This worked for me. Thank you.
public function up() { Schema::create('companies', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->text('address'); $table->string('tel1'); $table->string('tel2'); $table->integer('owner'); $table->unsignedBigInteger('access_id'); $table->string('depot_number')->default(2); $table->timestamps(); $table->foreign('access_id')->references('id')->on('accesses') ->onDelete('cascade'); }); }
public function up() { Schema::create('accesses', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('type'); $table->string('description'); $table->timestamps(); }); }
In your database/migrations folder, sort by name. Then make sure create_accesses_table is before create_companies_table:
enter image description here

Cannot create foreign key

I want to create a foreign key that is string from table "stocks" to "rfids".
The two tables are shown below.
stocks table:
Schema::create('stocks', function (Blueprint $table) {
$table->increments('tag_no');
$table->string('stock_type');
$table->string('rfid');
$table->foreign('rfid')->references('RFID_UID')->on('rfids');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
rfids table:
Schema::create('rfids', function (Blueprint $table) {
$table->increments('id');
$table->string('RFID_UID');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
When i use php artisan migrate it shows error.
SQLSTATE[HY000]: General error: 1005 Can't create table hardware.#sql-81c_c8 (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table stocks
add constraint stocks_rfid_foreign foreign key (rfid) references rfids (RFID_UID))
Someone help me pls!
The migration order is crucial. You have to create the referenced table (rfids) first.
You can order the migrations by changing the date/time in the filename.
I changed the tables this way:
Schema::create('rfids', function (Blueprint $table) {
$table->increments('id');
$table->string('RFID_UID');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
Schema::create('stocks', function (Blueprint $table) {
$table->increments('tag_no');
$table->string('stock_type');
$table->string('rfid');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
Instead of using foreign key i did the following while storing
public function store(Request $request)
{
//
if(Auth::check()){
if (Stock::where('tag_no','=',$request->input('tag_no'))->exists()) {
return back()->withInput()->with('errors', 'Tag number already used!');
}
$rfid_tag = Rfid::where('id',"=",$request->input('tag_no'))->first();
$stock = Stock::create([
'tag_no' => $request->input('tag_no'),
'stock_type' => $request->input('stock_type'),
'species' => $request->input('species'),
'rfid'=>$rfid_tag->RFID_UID,
'user_id' => Auth::user()->id
]);
if($stock){
return redirect()->route('stocks.index', ['stocks'=> $stock->tag_no])
->with('success' , 'Stock created successfully');
}
}
return back()->withInput()->with('errors', 'Error creating new Stock');
}
It works fine for me. But idk if its the right solution.

Resources