Laravel 5 - Composite key indexes in migrations - php

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

Related

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

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 rename column loss all data

I am new to Laravel and I create a users table using php artisan migrate command:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('username');
$table->string('email');
$table->string('password');
$table->rememberToken();
});
After that I just needed to change the username column as first_name then I change the schema as follows:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('first_name');
$table->string('email');
$table->string('password');
$table->rememberToken();
});
If I run the php artisan migrate command again, it says Nothing to migrate, then I used rollback, and I lose all table data.. How can I edit table structure without affecting my data? I hate Laravel doc
Let's start with your schema. Your table name is users. It contains a column named username and you want to change it to first_name without losing existing data. You need to create a new migration for this change.
php artian make:migration rename_columns_to_users_table --table=users
A new migration file will be created in your migrations directory. Open it and change it like this:
Schema::table('users', function ($table) {
$table->renameColumn('username', 'first_name');
});
Save it and then again run
php artisan migrate
You column name will be renamed immediately without losing your old data. Hope you got it now.
You will find more details here: https://laravel.com/docs/5.3/migrations#renaming-columns
You should create and register new migration and use Schema::table() and renameColumn() methods to rename a column:
Schema::table('users', function ($table) {
$table->renameColumn('from', 'to');
});
To rename a column, you may use the renameColumn method on the Schema builder.

Laravel migration blows up on foreign key. Already using unsigned int and referencing created tables

I am racking my brain trying to figure this out, but to no avail. Please help.
I have the following code:
Schema::create('inventory_category_relations', function(Blueprint $table)
{
$table->increments('id');
$table->integer('inventory_category_id')->unsigned()->nullable()->default(null);
$table->foreign('inventory_category_id')->references('id')->on('inventory_categories');
$table->integer('inventory_id')->unsigned()->nullable()->default(null);
$table->foreign('inventory_id')->references('id')->on('inventory');
$table->timestamps();
$table->softDeletes();
});
The above code references an 'inventory' and 'inventory_categories' table, which tables are already created and referenced by other tables, which work perfectly. However, every time I try to run "php artisan migrate" with the above code, my terminal blows up.
Edit
Here are my original 'inventory' and 'inventory_categories' create statements:
Schema::create('inventory_categories', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->timestamps();
$table->softDeletes();
});
Schema::create('inventory', function(Blueprint $table)
{
$table->increments('id');
$table->string('title');
$table->mediumText('basic_description');
$table->unsignedInteger('inventory_type_id');
$table->foreign('inventory_type_id')->references('id')->on('inventory_types')->onDelete('cascade');
$table->unsignedInteger('vendor_id');
$table->foreign('vendor_id')->references('id')->on('vendors')->onDelete('cascade');
$table->unsignedInteger('inventory_category_id');
$table->foreign('inventory_category_id')->references('id')->on('inventory_categories')->onDelete('cascade');
$table->decimal('price',10,2);
$table->decimal('compare_price',10,2);
$table->integer('quantity');
$table->string('sku');
$table->string('barcode');
$table->boolean('no_stock_purchase')->default(0);
$table->boolean('shipping_address')->default(0);
$table->decimal('shipping_weight')->default(0);
$table->boolean('free_shipping')->default(0);
$table->boolean('taxes')->default(1);
$table->boolean('multiple_options')->default(0);
$table->boolean('custom_variants')->default(0);
$table->boolean('active')->default(1);
$table->boolean('has_publish_date')->default(0);
$table->dateTime('start_date');
$table->dateTime('end_date');
$table->string('url');
$table->string('meta_title');
$table->mediumText('meta_description');
$table->boolean('has_commission')->default(0);
$table->unsignedInteger('created_by');
$table->foreign('created_by')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
$table->softDeletes();
});
I am using laravel 4.2 on a wamp server
Update:
Ok I used "php artisan migrate > migrate_error.log" and posted the results to pastebin. The file was too large, but I posted what would fit:
http://pastebin.com/J8KZn7R5
What you've got there is a stack trace due to a failed SQL statement. It's saying that it can't add the foreign key constraint of inventory_category_relations.inventory_category_id to reference inventory_categories.id.
My thought would be to remove the following portion
->nullable()->default(null)
from the two column creation statements in your inventory_category_relations migration. The columns they both reference are auto-incremented primary key IDs; those should never resolve to NULL anyway.
I solved it:
It turns out my database configurations were wrong. My tables were configured to MyISAM, when they should have been InnoDB.

Categories