Laravel 5.2 : `php artisan migrate` 's error - php

I am using Laravel 5.2 ,there is an error when I run php artisan migrate,as follows:
2016_06_12_134655_create_categories_table.php
public function up() {
Schema::create('categories', function(Blueprint $table) {
$table->increments('id');
$table->string('category');
$table->timestamps();
});
}
2016_06_12_134659_create_goods_table.php
public function up() {
Schema::create('goods', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('unit_price');
$table->integer('user_id')->unsigned();
$table->tinyInteger('category_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('category_id')->references('id')->on('categories');
$table->timestamps();
});
}
$php artisan migrate
what should I do?

It might be complaining about your use of tinyInteger on category_id, try setting it to integer as well - assuming your categories table exists. If it does not, you need to make sure any migrations with a foreign key constraint have their related tables migrated before them. Without seeing your categories table, I might wonder whether the datatype for your id is the same as well.

The referenced table categories has a primary key of type int. Keep the same in the referencing column category_id if You want to keep foreign key constraints, defined in line:
$table->foreign('category_id')->references('id')->on('categories');

When you use primary key $table->Increments('id');
you should use Integer as a foreign key
$table-> unsignedInteger('fk_id');
$table->foreign('fk_id')->references('id')->on('table_name');
When you use primary key $table->tinyIncrements('id');
you should use unsignedTinyInteger as a foreign key
$table-> unsignedTinyInteger('fk_id');
$table->foreign('fk_id')->references('id')->on('table_name');
When you use primary key $table->smallIncrements('id');
you should use unsignedSmallInteger as a foreign key
$table-> unsignedSmallInteger('fk_id');
$table->foreign('fk_id')->references('id')->on('table_name');
When you use primary key $table->mediumIncrements('id');
you should use unsignedMediumInteger as a foreign key
$table-> unsignedMediumInteger('fk_id');
$table->foreign('fk_id')->references('id')->on('table_name');

Related

Set non primary column as Auto Increment in Laravel

This is my migration file code
Schema::create('hierarchies', function (Blueprint $table) {
$table->integer('id');
$table->integer('hierarchy_id');
$table->timestamps();
});
I want my ID column will be auto increment without primary and hierarchy_id will be my primary key.
How to do that?
After a quick look through the Laravel Migrations manual pages I think thi sshoudl do waht you want, the thing to remember is you need to make the id column unique for it to still be allowed to be a Auto Increment.
Schema::create('hierarchies', function (Blueprint $table) {
$table->integer('id')->unique();
$table->integer('hierarchy_id')->autoIncrement();
$table->timestamps();
$table->primary('hierarchy_id');
});

PHP Laravel PDOException General error referencing column and referenced column in a foreign key constraint are incompatible

I am currently doing migrations in Laravel via the Terminal, and have these two errors when attempting to use php artisan migrate; I will print errors below:
Exception trace:
1 PDOException::("SQLSTATE[HY000]: General error: 3780 Referencing column 'room_id' and referenced column 'id' in foreign key constraint 'contacts_room_id_foreign' are incompatible.")
/Users/shaquilenoor/Desktop/chatapi/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
2 PDOStatement::execute()
/Users/shaquilenoor/Desktop/chatapi/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
Based on the code contained within the Exception Trace, the issue seems to be within the code below:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateContactsTable extends Migration
{
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user1_id');
$table->unsignedInteger('user2_id');
$table->integer('room_id')->unique();
$table->timestamps();
$table->foreign('room_id')->references('id')->on('rooms');
$table->foreign('user1_id')->references('id')->on('users');
$table->foreign('user2_id')->references('id')->on('users');
});
}
public function down()
{
Schema::dropIfExists('contacts');
}
}
any ideas on how I can resolve?
If you're on Laravel 5.8 new migration changed to big increments, so for fixining refrencing error just change integer to bigInteger, for example:
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
Will changed to:
$table->bigInteger('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
Either change original migration
from
bigIncrements()
to just
increments();
Or In your foreign key column do
bigInteger()
instead of
integer()
The foreign key must be the same as the referencing id,
and hence change
$table->integer('room_id')->unique();
to
$table->unsignedBigInteger('room_id')->unique();
and it does the trick.
PS: you'll get another error
SQLSTATE[42S01]: Base table or view
already exists: 1050 Table...
just delete the table and run php artisan migrate
In Laravel 6.0, migrations are as same as #Payam Khaninejad mentioned. i.e.
$table->bigInteger('user_id')->unsigned()->index();
I am updating that for Laravel 6.0 because, I was following an old tutorial that has shown the same error.
users table
$table->increments('id');
contacts table
$table->integer('user_id')->unsigned(); //adding unsigned() here, will fix the error
$table->foreign('user_id')->references('id')->on('users');
In this case, room_id should be unsigned. Try this:
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user1_id');
$table->unsignedInteger('user2_id');
$table->integer('room_id')->unique()->unsigned();
$table->timestamps();
$table->foreign('room_id')->references('id')->on('rooms');
$table->foreign('user1_id')->references('id')->on('users');
$table->foreign('user2_id')->references('id')->on('users');
});
}
Also in laravel 7.x you may have to change:
$table->increments('id'); // UNSIGNED INTEGER
// to
$table->id(); // UNSIGNED BIGINT
It seems that it is an issue with tables that were migrated in older versions. Ive got the same problem and in my case I used two differents types of declaration for each foreign keys. "integer" and "unsignedInteger"
$table->integer('webcam_id');
$table->unsignedInteger('user_id');
$table->foreign('webcam_id')
->references('id')
->on('webcam');
$table->foreign('user_id')
->references('id')
->on('users');
I recently ran into this problem during a migration to create a table with a foreign key constraint. I found that it had to due with the collation used on the table. Our DB schema is loaded with a schema file, and that has the table collation set to utf8mb4_0900_ai_ci. It looks like Laravel uses utf8mb4_unicode_ci by default.
I resolved the problem by setting the collation for the table during creation with $table->collation = 'YOUR_COLLATION_VALUE'
For Laravel 8.x, change $table->integer('user_id')->unsigned()->index(); to:
$table->unsignedBigInteger('user_id'); because this is compatible with the id() data type.
in your room migration, change the id as such
$table->id();
it will automatically create bigInteger with name 'id'
then in your contact migration, use
$table->bigInteger('room_id')->references('id')->on('rooms');
same goes to the other foreign keys, just follow above code.
well at least this syntax works on laravel 8
This is due to the foreign keys being set before the rooms table being created. you can fix this by doing the following.
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateContactsTable extends Migration
{
public function up()
{
Schema::disableForeignKeyConstraints();
Schema::create('contacts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user1_id');
$table->unsignedInteger('user2_id');
$table->integer('room_id')->unique();
$table->timestamps();
$table->integer('room_id')->unsigned();
$table->integer('user1_id')->unsigned();
$table->integer('user2_id')->unsigned();
$table->foreign('room_id')->references('id')->on('rooms');
$table->foreign('user1_id')->references('id')->on('users');
$table->foreign('user2_id')->references('id')->on('users');
});
Schema::enableForeignKeyConstraints();
}
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('contacts');
Schema::enableForeignKeyConstraints();
}
}

Laravel 5.7 foreign key constraint is incorrectly formed

Basically I'm trying to upload my migrations to the database, but I'm having some issues because I'm trying to reference columns from tables that aren't created yet. I thought about migrating them 1 by 1, but for example I have group and user tables. The group has a creator (user), and the user have a group. So I cannot reference them in the same time, because they're not created.
Here is my error:
PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `vote-system`.`#sql-1a08_37` (errno: 150 "Foreign key constraint is incorrectly formed")")
Group Migration
public function up()
{
Schema::create('groups', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('created_by')->unsigned();
$table->timestamps();
// Relationships
$table->foreign('created_by')->references('id')->on('users');
});
}
User Migration
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->ipAddress('ip');
$table->integer('votes_left');
$table->rememberToken();
$table->timestamps();
$table->integer('group_id')->unsigned();
// Relationships
$table->foreign('group_id')->references('id')->on('groups');
});
}
The correct way would be to create migrations for creating/dropping tables with lower timestamps (so these are executed first),
then just add/drop all your foreign keys with migrations with timestamps greater than previously used. This way you won't get into issue like you do now.
Example of the migration to add foreign keys:
class AddForeignKeysToMyTableTable extends Migration {
public function up()
{
Schema::table('my_table', function(Blueprint $table)
{
$table->foreign('my_field_id', ...
You may also wanna try some generator to create all the migrations for you. This one will make sure all your table-making migrations run before the ones to add foreign keys:
https://github.com/Xethron/migrations-generator

laravel errno 150 foreign key constraint is incorrectly formed

Can anybody help me to solve this problem?
There are 3 tables with 2 foreign keys:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('firms', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
Schema::create('jobs', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->nullable();
$table->integer('firm_id')->unsigned()->nullable();
$table->foreign('firm_id')->references('id')->on('firms');
$table->timestamps();
});
Error after running migration:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table `job`.`#sql-5fc_a1`
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter ta
ble `firms` add constraint `firms_user_id_foreign` foreign key (`user_id`)
references `users` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table `job`.`#sql-5fc_a1`
(errno: 150 "Foreign key constraint is incorrectly formed")
In case of foreign keys, the referenced and referencing fields must have exactly the same data type.
You create the id fields in both users and firms as signed integers. However, you create both foreign keys as unsigned integers, therefore the creation of the keys fail.
You need to either add the unsigned clause to the id field definitions, or remove the unsigned clause from the foreign key fields.
This answer is not better than the six answers before it but it is a more comprehensive answer on what causes laravel-errno-150-foreign-key-constraint-is-incorrectly-formed and how to fix specifically for laravel.
1) Spelling : often at times a wrong spelling of the referenced column name or referenced table name can throw up this error and you won't know as the error trace is not very descriptive.
2) Unique : the referenced column must be unique or indexed either by adding ->primary() or adding ->unique() or adding ->index() to the column definition in your migration.
3) Data type : the referenced and referencing fields must have exactly the same data type. this can not be stressed enough.
for bigincrements expected data type is bigInteger('column_name')->unsigned();
for increments expected is integer('column_name')->unsigned(); etc.
4) Remnants : when this error occurs it does not mean that the table is not migrated rather it is migrated but the foreign key columns are not set and it is not added to the migration table hence running php artisan migrate:reset will remove other tables except the faulty tables, so a manual drop of the faulty table is recommended to avoid further errors.
5) Order : this is often the most usual cause of this error the table being referenced must be created or migrated before the reference table else artisan wont find where to integrate the foreign key. to ensure an order for the migration process rename the migration file example:
Table A:2014_10_12_000000_create_users_table.php and
Table B:2014_10_12_100000_create_password_resets_table.php
This indicates that Table A will always come before Table B to change that, i will rename Table B to 2014_10_11_100000_create_password_resets_table.php now it will migrate before Table A.
6) Enable Foreign Key : if all else fails then add Schema::enableForeignKeyConstraints(); inside your function up() before your migration code example:
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::enableForeignKeyConstraints();
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
To read more see laravel foreign key and laravel migrations
Mention any more fixes that i missed in the comments thanks.
Most of the time this kind of error occurs due to the datatype mismatch on both the table.
Both primary key table & foreign key table should use same datatype and same option.
For example:
users
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
orders
Schema::create('orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('product_id')->unsigned();
$table->foreign('product_id')->references('id')->on('products');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamp('added_on');
});
On above example, I am trying to assign foreign key to users table from order table but I have bigInteger datatable in order table while in user table, I have simple integer. That's why it's generated this kind of error.
Also, If you have used unsigned(), nullable() etc options with primary or foreign key then you should use same at both the place.
For PHP laravel 5.8 use unsigned modifier in this format
$table->unsignedBigInteger('user_id');
drop all tables in the database and run the migration again
users
cashier refers users
student refers cashier
In addition when declaring foreign keys in laravel all tables your are referring must be on the top. In this case you can use "->unsigned()" modifier..
If the reference table primary key is in BigIcrements then Use the BigInteger for foreign key also like below
Table ATable
public function up()
{
Schema::create('a_tables', function (Blueprint $table) {
$table->bigIncrements('id');
}
}
TABLE BTable
public function up()
{
Schema::create('b_tales', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('a_tables_id')->unsigned();
$table->foreign('a_tables_id')->references('id')->on('a_tables')->onDelete('cascade');
}
}
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 here:
we are table villes:
Schema::create('villes', function (Blueprint $table) {
$table->bigIncrements('idVille'); // bigIncrement(8 bits)
$table->string('nomVille');
$table->timestamps();
});
foreign key in table users for exemple :
Schema::table('users', function (Blueprint $table) {
$table->bigInteger('ville_idVille')->unsigned()->after('tele');
$table->foreign('ville_idVille')->references('idVille')->on('villes');
});
if you set referencing fields and be have exactly the same data type but error exists
you can change date migration file
just its working
I tried all the answers provided in this thread.
Nothing worked.
Then I discovered I forgot to remove the "migrations" table in phpMyadmin.
I removed all tables from phpMyAdmin but the migrations table. That's why the error persisted again and again.
Well this answer is related to Laravel 7.x. So the error:
errno: 150 "Foreign key constraint is incorrectly formed"
can occur due many reason while migrating the migrations. The one common reason that I am familiar about is order of migration.
Lets say we have two table "users" and "roles", and "users" table have a foreign key referring the "id" column on "roles" table. So make sure that "roles" is migrated before "users" table.
So order of migration is important. Its obvious as it does not make sense for MySQL to refer to "id" column of unknown table.
Second reason is wrong data type. In laravel 7.x we use "id()" method for primary key. So make sure that the intended foreign key (in my case "role_id" in "users" table) is of "bigInteger" and is "unsigned".
Here my code:
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->nullable();
$table->timestamps();
});
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->bigInteger("role_id")->unsigned();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
public function down()
{
Schema::table('users', function(Blueprint $table)
{
$table->dropForeign('users_role_id_foreign');
});
Schema::dropIfExists('users');
}
So in the above code I had to migrate the "roles" table first then the "users" table. So MySQL can create foreign key for the roles table.
What is do is I move the child migration (migration having foreign key) to temporary folder. And restore it after migrating parent migration (in my case "roles" table and then migrate the child migration ("users" migration).
And as side tip: while dropping the dependent migration (migration containing foreign key) first drop the foreign key first. And Laravel uses specific naming convention while dropping foreign key "<table_name>_<foreign_key>_foreign".
So happy coding and be ready for Ground breaking release of PHP 8.
Here the main concept is you have to ensure same type of primary key and foreign key. For example, Let your 1st table migration is
public function up()
{
Schema::create('chapters', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->timestamps();
});
}
Then your 2nd table migration will be
public function up()
{
Schema::create('classifications', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->unsignedBigInteger('chapter_id');
$table->timestamps();
$table->foreign('chapter_id')->references('id')->on('chapters')->onDelete('cascade');
});
}
Here "id" in "chapter" table and "chapter_id" in " classifications " table are same and that is "unsignedBigInteger".
Again if you get error then change " $table->id(); " in "chapter" table by " $table->bigIncrements('id'); ".
Hope this will help you
for the laravel 7 migration error as
("SQLSTATE[HY000]: General error: 1005 Can't create table laraveltesting.reviews (errno: 150 "Foreign key constraint is incorrectly formed")")
order of migration is most important so parent table should be migrated first then only child
Image 1:migration order while getting error
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('detail');
$table->float('price');
$table->integer('stock');
$table->float('discount');
$table->timestamps();
});
Schema::create('reviews', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained('products')->cascadeOnDelete();
$table->string('customer');
$table->text('review');
$table->integer('star');
$table->timestamps();
});
this causes the error while migrating this can be resolved by changing the order of migration by renaming the migration as shown in image 2 from the image 1. books table should be migrated first then only the review table should be migrated
Image 2:Order of migration for the successful migration
if you get error change $table->id()(references) by $table->increments('id')
worked with me after all Efforts
delete (user table) from both database and (migration table) then "uncomment" your foreign key Relations
example :
$table->string('pass1');
$table->foreign('pass1')->references('email')->on('abs');
then run : php artisan migrate
well run successfully
sometime your query syntax is true but this error is occur because you create your table unorderly if you want to make relation between table let's suppose you wanna a create many to many relationship between "user" and "role" table for this you should migrate user and role table first then create "role_user" table else you face error like this.
For more details check my screenshot.
enter image description here
in laravel 9 i got same error while creating foreign key for my posts table
SQLSTATE[HY000]: General error: 1005 Can't create table `wpclone`.`posts` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `posts` add constraint `posts_author_id_foreign` foreign key (`author_id`) references `users` (`id`) on delete restrict)
and my table looks like this:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->integer('author_id')->unsigned();
$table->foreign('author_id')->references('id')->on('users')->onDelete('restrict');
$table->string('title');
});
after i found solution that in laravel 9 unsigned modifier in this format work well
$table->unsignedBigInteger('author_id');
and my error was solve. hope this will help you. Thanks

Laravel Migrations self-referencing foreign key General error: 1005 Can't create table

Why do I have a problem creating a table using Laravel Migrations Schema Builder?
The problem occurs with a table with a self-referencing foreign key.
Schema::create('cb_category', function($table)
{
$table->integer('id')->primary()->unique()->unsigned();
$table->integer('domain_id')->unsigned();
$table->foreign('domain_id')->references('id')->on('cb_domain');
$table->integer('parent_id')->nullable();
$table->foreign('parent_id')->references('id')->on('cb_category')->onUpdate('cascade')->onDelete('cascade');
$table->string('name');
$table->integer('level');
});
SQLSTATE[HY000]: General error: 1005 Can't create table 'eklik2.#sql-7d4_e' (errno: 150) (SQL: alter table `cb_category` add constraint cb_category_parent_id_foreign foreign key (`parent_id`) references `cb_category` (`id`) on delete cascade on update cascade) (Bindings: array ())
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table 'eklik2.#sql-7d4_e' (errno: 150)
You have to break this into two Schema blocks, one creating the columns, the other adding the FKs. mysql can't do both at the same time.
Two querys work :
Schema::create('cb_category', function($table)
{
$table->integer('id')->primary()->unique()->unsigned();
$table->integer('parent_id')->nullable();
});
Schema::table('cb_category', function (Blueprint $table)
{
$table->foreign('parent_id')->references('id')->on('cb_category')->onUpdate('cascade')->onDelete('cascade');
});
I may be too late for the party, but the official docs claim that the foreign key, in case of integer, must be ->unsigned();
http://laravel.com/docs/4.2/schema#foreign-keys
Note: When creating a foreign key that references an incrementing
integer, remember to always make the foreign key column unsigned.
Also, Artisan does not fail if you (as I have) misspell unsigned() and I have spent quite a few hours trying to figure out why the key was not created.
So two things:
1. Always make the foreign key column unsigned in case of incrementing integers
2. Check the spelling of unsigned()
Also a late response but probably a more idiomatic way for Laravel 8:
use App\Models\CbCategory;
...
Schema::create("cb_category", function(Blueprint $table)
{
$table->id();
$table->foreignIdFor(CbCategory::class, "parent_id")
->constrained()
->cascadeOnUpdate()
->cascadeOnDelete()
->nullable();
});
Please Note: I guessed the class name of CbCategory here. Using the class reference firsthand (instead of the former table name string) enables your static code checkers to pick up on future class name changes.
Also the _id-suffix at the parent_id column name is important.
May the following resources quench your thirst for knowledge:
id(): https://laravel.com/docs/8.x/migrations#column-method-id
foreignIdFor(): https://laravel.com/api/8.x/Illuminate/Database/Schema/Blueprint.html
cascadeOnDelete() & cascadeOnUpdate(): https://laravel.com/api/8.x/Illuminate/Database/Schema/ForeignKeyDefinition.html
Schema::create('cb_category', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('domain_id')->unsigned();
$table->foreign('domain_id')->references('id')->on('cb_domain');
$table->integer('parent_id')->nullable();
$table->foreign('parent_id')->references('id')->on('cb_category')->onUpdate('cascade')->onDelete('cascade');
$table->string('name');
$table->integer('level');
});
Try this
I think you have another table that references the current table that you want to create.
I had this problem and remove that table and my problem was solved
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->integer('parent_id')->unsigned();
$table->foreign('parent_id')->on('categories')->references('id');
});
i got same error when i used this code, after change "$table->integer('parent_id')->unsigned()" to "$table->bigInteger('parent_id');"
my problem solved.
The point here is to make sure that the type of foreign key is the same as the primary key.
Since Laravel 8+ you don't have to break into two Schema blocks. You can use
foreignIdFor(CbCategory::class, 'cb_category_id') and it will create a column named cb_category_id
Ex.
Schema::create("cb_category", function(Blueprint $table)
{
$table->id();
$table->foreignIdFor(CbCategory::class, 'cb_category_id')->nullable()->constrained()->cascadeOnUpdate()->cascadeOnDelete();
});
Any additional column modifiers (Ex. nulleable) must be called before the constrained method.
You can use a second parameter in foreignIdFor for the referencing column name (in case it isn't 'id') NOT for the name you want it to have, in your case the name will automatically be 'cb_category_id'

Categories