Set non primary column as Auto Increment in Laravel - php

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');
});

Related

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();
}
}

SQLSTATE[HY000] Error in Laravel: failing to add foreign key

I have tried almost all the answers here, my migrations are in order, I have set the engine to 'InnoDB', I have set the user_types_id to unsigned. I think I am missing out on something, I am not able to migrate this. ( I was able to manually add the FK from phpMyAdmin though).
My user-types are created before my users table is created, I did ensure that :)
Migrations:
Schema::create('user-types',function(Blueprint $table){
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('name');
$table->timestamps();
});
and the users table:
// I think I saw this somewhere, too
Schema::enableForeignKeyConstraints();
Schema::create('users',function(Blueprint $table){
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('name');
$table->string('password');
$table->integer('user_types_id')->unsigned()->nullable();
$table->timestamps();
});
Schema::table('users',function(Blueprint $table){
// When I index it I am able to manually add fk from
// phpMyAdmin
$table->index('user_types_id');
$table->foreign('user_types_id')->references('id')->on('user_types');
});
There is name differences in your schema defination.
You are creating table with Schema::create('user-types',function(.... where table name is user-types but when you are setting up foreign key you are passing user_types
So make them same whichever is correct. Either user-types or user_types and then it will work.
You can give reference like this also
Schema::create('users',function(Blueprint $table){
$table->engine = 'InnoDB';
$table->increments('id');
$table->foreign('user_types_id')->references('id')->on('user-types')->onDelete('cascade');
$table->string('name');
$table->string('password');
$table->integer('user_types_id')->nullable();
$table->timestamps();
});
Schema::enableForeignKeyConstraints(); //Remove this its not require,
I think you need to write,
Schema::disableForeignKeyConstraints(); // disable foreign key checks while creating tables which are dependant on each other
at the top of your schema definition where you are facing this problem, it should work.

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 5.2 : `php artisan migrate` 's error

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');

Laravel 5 - Composite key indexes in migrations

Composite indexes are a subject I'm not fully experienced in, I wasn't sure if I was doing it right? Or if Laravel is parsing my code correctly when migrating. Does this look correct?
Schema::create('friends', function(Blueprint $table)
{
$table->increments('id');
$table->integer('requester_id')->unsigned();
$table->integer('requestee_id')->unsigned();
$table->timestamps();
$table->foreign('requester_id')->references('id')->on('users');
$table->foreign('requestee_id')->references('id')->on('users');
$table->unique(['requester_id', 'requestee_id'], 'composite_index');
});
Here is what Sequel Pro shows:
http://i.imgur.com/5A4LZH3.png
What you have there is correct.
Note: you don't have to specify the index's name. Laravel will automatically generate a name for you based on the columns being indexed.
Here's my example: creating unique external_id for every user user_id:
Schema::create('orders', function (Blueprint $table) {
$table->increments('id');
$table->string('external_id')->nullable();
$table->unique(['external_id', 'user_id']); // <<---------
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
// ...
});

Categories