I have posts table:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('imid');
$table->string('name');
$table->text('body');
$table->timestamps();
});
and
images table:
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('imid');
$table->string('name')->nullable();
$table->longText('image_path')->nullable();
$table->timestamps();
});
I am trying to add a foreign field to existing posts table in a separate migration:
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->foreign('imid')->references('imid')->on('images')->onDelete('cascade');
});
}
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('imid');
});
}
But when I run
php artisan migrate
I get error:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `posts` add constraint `posts_imid_foreign` foreign key (`imid`) references `images` (`imid`) on delete cascade)
It seems I do it right. What am I missing here?
Check that both your tables have the columns for which you create the foreign key (imid) and that these columns have the same types. You can use the following commands to do this:
DESCRIBE posts;
DESCRIBE images;
Next, check if posts table has no imid values which point to non-existing records in the images table (If they are - connect them to existing ones or remove them)
SELECT posts.id, posts.imid FROM posts
LEFT JOIN images ON posts.imid = images.imid
WHERE images.id IS NULL;
Make sure your tables are using InnoDB engine
SHOW TABLE STATUS WHERE name = 'posts';
if Engine != InnoDB then run:
ALTER TABLE posts ENGINE = InnoDB;
Finally, I suggest that you change the down method of your migration so that it does the reverse of the up method:
Schema::table('posts', function (Blueprint $table) {
$table->dropForeign('posts_imid_foreign');
});
Friends I have the following problem with laravel migrations using postgres, and when I make changes to a migration, in this case the users table, but I get an error trying to remove an index from a key, can you help me please with this problem.
This is my migration code:
public function up() {
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->integer('idProfile');
$table->string('name');
$table->string('surname');
$table->string('email')->unique();
$table->string('photo')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down() {
Schema::dropIfExists('users');
Schema::table('users', function (Blueprint $table){
$table->dropPrimary('id');
$table->dropIndex('users_pkey');
});
}
response from my console:
These are the indices that list me:
This is the structure of the final table:
Comments, things to improve I am all ears
When you are running migrate:refresh, you are running the down method. In your down method, you are dropping the table, and then trying to make edits to it, which is why you are getting "users" doesn't exist.
If this is just in a development env, make your changes in the up method, and remove everything apart from dropIFExists() from the down method.
It is highly recommended that don't change the migration file...
If you need to add a new row to your table (Consider you have mytable and you want to add myrow to the table), you can write in terminal :
php artisan make:migration add_myrow_to_mytable_table
after that , edit new added migration file!
remember to add the following code in down function :
Schema::table('mytable', function (Blueprint $table) {
$table->dropColumn('myrow');
});
after all, run :
php artisan migrate
If you want to remove a column from your table just follow this one :
Laravel Migrations - Dropping columns
I want to write a Laravel Migration auto increment ID as a primary key. I want to start this ID with a another value rather than 1. How can I do so ?
The migration up() function:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->string('phone');
$table->rememberToken();
$table->timestamps();
});
}
As of Laravel 8.x, you can now use this in your migration:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id()->startingValue(1200);
});
}
Source: https://laravel-news.com/laravel-auto-increment
You can use 2 methods
By Statement
DB::statement("ALTER TABLE your_table_here SET AUTO_INCREMENT = 9999;");
By inserting row and deleteing it.
DB::table('your_table_here ')->insert(['id' => 99999, ... ,'column' => 'value']);
DB::table('your_table_here ')->where('id', 99999)->delete();
Hope this helps
If you want your first ID in the table to be for example 10001.
If you are using Laravel 8.x
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id')->from(10001);
.
.
$table->timestamps();
});
}
add a record with id (desired id -1) and then delete it.
If you add a record with id 999, and then delete it, next record will have id 1000. You can also use SQL identity on your database
After Creating Migrations Just Go to your Mysql Database and put this query
ALTER TABLE users AUTO_INCREMENT = 1000;
try this ?
$table->increments('id')->start_from(10000);
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.
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