Hey guys I tried too much stuff and read some blogs or discussion I didn't fix my problem I'm new in laravel this project. I got error when I want to create to database this error like
PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `portal`.`employees` (errno: 150 "Foreign key constraint is incorrectly formed")")
my migration for payments:
public function up()
{
Schema::create('payments', function (Blueprint $table) {
$table->bigInteger('id');
$table->unsignedBigInteger('employee_id');
$table->decimal('salary',16);
$table->decimal('amount_paid',16);
$table->unsignedBigInteger('paid_by');
$table->string('remark');
$table->string('department',50);
$table->timestamps();
});
Schema::table('payments', function($table) {
$table->foreign('employee_id')->references('id')->on('employees')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('paid_by')->references('id')->on('users');
});
}
my migration for employees:
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->unsignedBigInteger('id');
$table->string('name');
$table->string('department');
$table->string('location');
$table->string('telephone');
$table->decimal('salary',16);
$table->string('cover_image');
$table->foreign('department')->references('name')->on('departments')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
Department Table:
public function up()
{
Schema::create('departments', function (Blueprint $table) {
$table->bigInteger('id');
$table->string('name');
$table->timestamps();
});
}
my migration folder:
https://i.stack.imgur.com/pCsbg.png
making foreign keys on non unique columns is not a good idea, and only innodb for mysql support that, see mysql doc.
instead of:
$table->foreign('department')->references('name')->on('departments')->onUpdate('cascade')->onDelete('cascade');
you should make the foreign key regularly like:
$table->bigInteger('department_id');
$table->foreign('department_id')->references('id')->on('departments')->onUpdate('cascade')->onDelete('cascade');
You can simply set the foreign key on the department Id and of course, it's much better and has better performance setting a foreign key on unique keys.
Im trying to do a many to many relationship, where many brand has many product types and also has many models. And many product types has many brands:
So this are my eloquent relationships:
Ptype.php:
class Ptype extends Model
{
public function marca(){
return $this->belongsTo(Brand::class, 'brand_id', 'id');
}
}
Brand.php:
public function ptype(){
return $this->hasMany(Ptype::class, 'ptype_id', 'id');
}
Migrations:
brands_table:
public function up()
{
Schema::create('models', function (Blueprint $table) {
$table->id();
$table->string('modelName');
$table->unsignedBigInteger('brand_id');
$table->foreign('brand_id')->references('id')->on('brands');
$table->timestamps();
});
}
ptypes:
public function up()
{
Schema::create('ptypes', function (Blueprint $table) {
$table->id();
$table->string('productType');
$table->unsignedBigInteger('brand_id');
$table->foreign('brand_id')->references('id')->on('brands');
$table->integer('created_by')->nullable();
$table->integer('updated_by')->nullable();
$table->timestamps();
});
}
What am i doing wrong?
This is the exact error:
SQLSTATE[HY000]: General error: 1005 Can't create table `axis`.`ptypes` (errno
: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `ptypes`
add constraint `ptypes_brand_id_foreign` foreign key (`brand_id`) references `b
rands` (`id`))
Firstly, check your migration files orders. As far as I see, they should be like this:
brands migration
models migration
ptypes migration
Also, you can use foreignId instead of foreign, references, etc.
$table->foreignId('brand_id')->constrained(‘brands’);
So, you can delete these;
$table->unsignedBigInteger('brand_id');
$table->foreign('brand_id')->references('id')->on('brands');
i cant figure out what im doing wrong, but everything looks ok, is giving me this errroof
Foreign key constraint is incorrectly formed
on my migrations, but i dont see any issue.
Migration table 1:
public function up()
{
Schema::create('candidate_industries', function (Blueprint $table) {
$table->increments('id');
$table->integer('candidate_id')->unsigned();
$table->foreign('candidate_id')->references('id')->on('candidates');
$table->integer('industry_id')->unsigned();
$table->foreign('industry_id')->references('id')->on('industries');
});
}
Migration number 2:
public function up()
{
Schema::create('candidate_regions', function (Blueprint $table) {
$table->increments('id');
$table->integer('candidate_id')->unsigned();
$table->foreign('candidate_id')->references('id')->on('candidates');
$table->integer('region_id')->unsigned();
$table->foreign('region_id')->references('id')->on('regions');
});
}
The issue was because "candidates" id column had a different dataType set, in my case was BigInt when i was trying to create a relation with a column of int.
The Problem
I want to add foreign keys to tables. When I run my first migration create_posts_table that looks like this:
Schema::create('posts', function(Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->unsignedInteger('user_id')->index();
// . . .
});
Schema::table('posts', function(Blueprint $table)
{
$table->foreign('user_id')->references('id')
->on('users')->onDelete('cascade');
});
The following error is thrown:
[Illuminate\Database\QueryException] SQLSTATE[HY000]:
General error: 1215 Cannot add foreign key constraint (SQL: alter table
posts add constraint posts_user_id_foreign foreign key (user_id) references users (id) on delete cascade)
This is caused because the users table is not created yet, hence the failure to create the users' referencing foreign key on the posts table.
Possible Solution
The solution to this problem would be to add the foreign keys with a new migration after all of the tables had been created. However, it seems clunky to me.
The question
How can I define the foreign keys inside their respective tables' migrations, instead of adding them separately with the different migration after all of the tables had been created?
You can perform multiple migrations in the same migration file. If you have a posts table where you want a foreign key to the users table, but the users table does not yet exist, you either have to do it in the users table migration file after the users table has been created - or you have to do a separate migration, like you said. You can't "save" instructions for later in migrations.
In laravel way is keeping separate migration files for different tables with indexing, primary key & foreign keys.....
CreateUsersTable
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('password', 60);
$table->enum('status', ['0', '1'])->default('0');
$table->rememberToken();
$table->nullableTimestamps();
$table->unique('email');
});
}
public function down()
{
Schema::drop('users');
}
}
CreatePostsTable
class CreatePostsTable extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
}
public function down()
{
Schema::drop('posts');
}
}
Simple question: I'm new to Laravel. I have this migration file:
Schema::create('lists', function(Blueprint $table) {
$table->increments('id');
$table->string('title', 255);
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
I want to update it to add onDelete('cascade').
What's the best way to do this?
Firstly you have to make your user_id field an index:
$table->index('user_id');
After that you can create a foreign key with an action on cascade:
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
If you want to do that with a new migration, you have to remove the index and foreign key firstly and do everything from scratch.
On down() function you have to do this and then on up() do what I've wrote above:
$table->dropForeign('lists_user_id_foreign');
$table->dropIndex('lists_user_id_index');
$table->dropColumn('user_id');
In Laravel 7 it can be done in one line
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
let's say you have two tables student and section , you can refer the following two table structure for adding foreign key and making onDelete('cascade') .
Table -1 :
public function up()
{
Schema::create('student', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('address');
$table->string('phone');
$table->string('about')->nullable();
$table->timestamps();
});
}
Table - 2:
public function up()
{
Schema::create('section', function (Blueprint $table) {
$table->id();
$table->bigInteger('student_id')->unsigned()->index()->nullable();
$table->foreign('student_id')->references('id')->on('student')->onDelete('cascade');
$table->string('section')->nullable();
$table->string('stream')->nulable();
$table->timestamps();
});
}
hope it will help you -:)
you can read the full article from here .
Schema::create('roles',function(Blueprint $table){
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
Schema::create('permissions',function(Blueprint $table){
$table->unsignedBigInteger('role_id');
$table->foreign('role_id')->references('id')->on('roles');
$table->string('permission');
});
As of Laravel 8:
$table->foreignIdFor(OtherClass::class)->constrained();
So simple :)
Make sure that the OtherClass migration file is running EARLIER (by filename date as usual).
If the OtherClass id is not autoincrementing, the otherclass_id would have a type of char instead of bigint, in which case->
Use this instead:
$table->foreignId('otherclass_id')->index()->constrained()->cascadeOnDelete();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
In this example, we are stating that the user_id column references the id column on the users table. Make sure to create the foreign key column first! The user_id column is declared unsigned because it cannot have negative value.
You may also specify options for the "on delete" and "on update" actions of the constraint:
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
To drop a foreign key, you may use the dropForeign method. A similar naming convention is used for foreign keys as is used for other indexes:
$table->dropForeign('posts_user_id_foreign');
If you are fairly new to Laravel and Eloquent, try out the Laravel From Scratch series available on laracasts. It is a great guide for beginners.
Laravel 7.x Foreign Key Constraints
Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a user_id column on the posts table that references the id column on a users table:
Schema::table('posts', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
Since this syntax is rather verbose, Laravel provides additional, terser methods that use convention to provide a better developer experience. The example above could be written like so:
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained();
});
Source: https://laravel.com/docs/7.x/migrations
You should create a new migration file let's say 'add_user_foreign_key.php'
public function up()
{
Schema::table('lists', function(Blueprint $table)
{
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('lists', function(Blueprint $table)
{
$table->dropForeign('user_id'); //
});
}
The run
php artisan migrate
If you want to add onDelete('cascade') on the existing foreign key, just drop the indexes and create them again:
public function up()
{
Schema::table('lists', function($table)
{
$table->dropForeign('lists_user_id_foreign');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
public function down()
{
Schema::table('lists', function($table)
{
$table->dropForeign('lists_user_id_foreign');
$table->foreign('user_id')->references('id')->on('users');
});
}
Schema::table('posts', function (Blueprint $table) {
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
for versions before 7x;
Schema::create('lists', function(Blueprint $table) {
$table->increments('id');
$table->string('title', 255);
$table->unsignedBigInteger('user_id')->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
for version 7+;
Since this syntax is rather verbose, Laravel provides additional, terser methods that use conventions to provide a better developer experience. When using the foreignId method to create your column, the example above can be rewritten like so:
Schema::create('lists', function(Blueprint $table) {
$table->increments('id');
$table->string('title', 255);
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
The foreignId method is an alias for unsignedBigInteger while the constrained method will use convention to determine the table and column name being referenced. If your table name does not match the convention, you may specify the table name by passing it as an argument to the constrained method:
Schema::create('lists', function(Blueprint $table) {
$table->foreignId('user_id')->constrained('users')->onDelete('cascade');
});
source: https://laravel.com/docs/7.x/migrations#foreign-key-constraints
Clear and new in laravel
$table->foreignId('book_id')->constrained();
I was doing the same but got error " id not exist" => so I changed my migration file as below :
question table migration content:
$table->id() => should change to $table->increments('id')
definitions of foreign key in Reply table:
$table->foreign('question_id')->references('id')->on('questions')->onDelete('cascade');
now your foreign key will work.
Clear, modern and Straightforward approach
suppose parent: `Book Model` and `books table`
suppose child : `Page Model` and `pages table`
$table->foreignId('book_id')->references('id')->on('books');
where book_id is is the colomn name in child (pages table)
and id is the linkage between the Parent and Child tables, books and pages tables, and books is the table name to which we are going to link