I'm trying to create foreign keys in Laravel however when I migrate my table using artisan I am thrown the following error:
Modules migration table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateModulesTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up() {
Schema::create('modules', function (Blueprint $table) {
$table->id();
$table->string('module_name');
// foreign key
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('modules');
}
}
Lesson migration table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateLessonTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up() {
Schema::create('lesson', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->integer('module_id')->unsigned();
$table->text('content');
$table->integer('created_by')->unsigned();
$table->integer('updated_by');
$table->string('enabled');
$table->string('position');
$table->timestamps();
});
Schema::table('lesson', function(Blueprint $table) {
$table->foreign('module_id')->references('id')->on('modules');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('lesson');
}
}
Any ideas as to what I've done wrong, I want to get this right now, as I've got a lot of tables I need to create e.g. Users, Clients, Projects, Tasks, Statuses, Priorities, Types, Teams. Ideally, I want to create tables that hold this data with the foreign keys, i..e clients_project and project_tasks, etc.
Hope someone can help me to get started.
Add unsignedBigInteger for module_id column
Schema::create('lesson', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->unsignedBigInteger('module_id');
$table->text('content');
$table->integer('created_by')->unsigned();
$table->integer('updated_by');
$table->string('enabled');
$table->string('position');
$table->timestamps();
$table->foreign('module_id')->references('id')->on('modules');
});
Your foreign_key field and your id should be of the same type, for example, if modules.id is bigIncrements, your foreign_key inside your Lesson table also should be bigInteger.
Lesson Migration File
Schema::create('lesson', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->integer('module_id')->unsigned()->nullable();
$table->foreign('module_id')->references('id')->on('modules')->onDelete('cascade');
$table->text('content');
$table->integer('created_by')->unsigned();
$table->integer('updated_by');
$table->string('enabled');
$table->string('position');
$table->timestamps();
});
Note: You should make sure, your Modules table migration is running before Lesson table migration.
Related
I'm trying to create foreign keys in Laravel however when I migrate my table using artisan I am thrown the following error:
Copy\vendor\laravel\framework\src\Illuminate\Database\Connection.php:465
PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server
version for the right syntax to use near 'unsigned not null, `updated_by` varchar(255) unsigned not null, `enabled` var...' at line 1")
Lessons migration table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateLessonTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('lesson', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->bigInteger('module_id')->unsigned();
$table->text('content');
$table->string('created_by')->unsigned();
$table->string('updated_by')->unsigned();
$table->string('enabled');
$table->string('position');
$table->timestamps();
});
Schema::table('lesson', function(Blueprint $table) {
$table->foreign('module_id')->references('id')->on('modules');
$table->foreign('created_by')->references('username')->on('admins');
$table->foreign('updated_by')->references('username')->on('admins');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('lesson');
}
}
Admins Migration Table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAdminsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->id();
$table->string('username');
$table->string('password');
$table->string('fname');
$table->string('mname');
$table->string('lname');
$table->string('email');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('admins');
}
}
I was trying to connect the created_by and updated_by columns of the Lessons table to the Admins table column 'username'. Both are in string already.
The problem is you're using unsigned on a column you're defining as a string, you can't have an unsigned string. As you're attempting to create a FK relationship between lessons and users, you likely want to use an integer column of some sort.
You could write your migration as follows:
public function up()
{
Schema::create('lesson', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->string('enabled');
$table->string('position');
$table->unsignedBigInteger('module_id');
$table->unsignedBigInteger('created_by');
$table->unsignedBigInteger('updated_by')->nullable();
$table->foreign('module_id')->references('id')->on('modules');
$table->foreign('created_by')->references('id')->on('admins');
$table->foreign('updated_by')->references('id')->on('admins');
$table->timestamps();
});
}
$table->string('created_by')->unsigned();
I think the problem is that unsigned is for numbers only not string
remove unsigned and try again
can someone please help me with this one? I'm new to Laravel and when I try to do:
php artisan migrate
I get the error:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table posts add constraint posts_author_id_foreign foreign key (author_id) references users (id) on delete restrict)
and this is the post table content:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('author_id')->unsigned();
$table->foreign('author_id')->references('id')->on('users')->onDelete('restrict');
$table->string('title');
$table->string('slug')->unique();
$table->text('excerpt');
$table->text('body');
$table->string('image')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
I have noticed that when I comment this line:
$table->foreign('author_id')->references('id')->on('users')->onDelete('restrict');
the error is gone, so I guess the problem is in that line. So, can someone please tell me what will be the correct syntax or how to fix it?
The column data type must be the same on both tables for the foreign key to work. By default, the users id column is:
$table->bigIncrements('id');
Therefore, you need to use bigInteger for your posts migration:
$table->bigInteger('author_id')->unsigned();
Try to change the foreign ko to unsignedInteger
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('author_id');
$table->foreign('author_id')->references('id')->on('users')->onDelete('restrict');
$table->string('title');
$table->string('slug')->unique();
$table->text('excerpt');
$table->text('body');
$table->string('image')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
i am trying to run command php artisan migrate:rollback and it throw me the error cannot update or delete a parent row foreign key constraint fails
there is now issue when i run command php artisan migrate it successfully migrate my all tables but when i run rollback command it throw me the error the error is on my purpose_of_visits migration
public function up()
{
Schema::create('purpose_of_visits', function (Blueprint $table) {
$table->increments('id');
$table->string('purpose', 100);
$table->string('description', 197);
$table->integer('speciality_id')->unsigned()->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
$table->softDeletes();
$table->integer('created_by')->unsigned()->nullable();
$table->integer('updated_by')->unsigned()->nullable();
$table->foreign('speciality_id')->references('id')->on('specialities')->onDelete('cascade');
$table->foreign('created_by')->references('id')->on('users')->onDelete('cascade');
$table->foreign('updated_by')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('purpose_of_visits');
}
and my specialities migration:
public function up()
{
Schema::create('specialities', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 50);
$table->string('description',250)->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
$table->softDeletes();
$table->integer('created_by')->unsigned()->nullable();
$table->integer('updated_by')->unsigned()->nullable();
$table->foreign('created_by')->references('id')->on('users')->onDelete('cascade');
$table->foreign('updated_by')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('specialities');
}
i cant figure out where is the issue even i am using onDelete('cascade')
your help will be highly appreciated!
Make sure you have speciality_id, created_by and updated_by in the fillable property of your purpose_of_visits model. See docs here.
For example on your model.
protected $fillable = ['speciality_id','created_by','updated_by'];
Remove the foreign key constraints of the table before dropping it.
public function down()
{
Schema::table('purpose_of_visits', function (Blueprint $table) {
$table->dropForeign(['speciality_id']);
$table->dropForeign(['created_by']);
$table->dropForeign(['updated_by']);
});
Schema::dropIfExists('purpose_of_visits');
}
Sorry For the Late reply There are Two Situation Where this error can be thrown
For Eg:
I have tables such as posts, authors
And here is my post table Migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->unsignedInteger('author_id');
$table->foreign('author_id')->references('id')->on('authors')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
and here is my authors table migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAuthorsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('authors', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('authors');
}
}
Situation 1:
now if the posts table migration runs before the authors table migration it my throw the error
Situation 2:
in some cases if you miss unsigned it may throw error
Solution1:
use
$table->unsignedInteger('speciality_id');
$table->unsignedInteger('speciality_id');
$table->foreign('author_id')->references('id')->on('specialities')->onDelete('cascade');
instead of this
$table->integer('speciality_id')->unsigned()->nullable();
$table->foreign('speciality_id')->references('id')->on('specialities')->onDelete('cascade');
if it again fails use this
try composer dumpautoload
adn then
Schema::disableForeignKeyConstraints();
At the beggining of the migration
and at the end
Schema::enableForeignKeyConstraints();
eg: you migration may look like
public function up()
{
Schema::disableForeignKeyConstraints();
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->rememberToken();
$table->timestamps();
$table->softDeletes();
});
Schema::enableForeignKeyConstraints();
}
and if the same error throws please attach Error Screenshot and commet below
Hope it helps
I am getting the following error when running migrations:
PDOException::("SQLSTATE[42S21]: Column already exists: 1060 Duplicate
column name 'role_id'")
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
if(!Schema::hasTable('users')) {
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->rememberToken();
$table->timestamps();
});
}
Schema::table('users', function (Blueprint $table) {
$table->integer('role_id')->unsigned();
$table->string('first_name')->nullable();
$table->string('middle_name')->nullable();
$table->string('last_name')->nullable();
$table->string('city')->nullable();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('role_id');
});
}
}
I have deleted most of the migrated tables as it gives duplication issues. Could that be related to my existing problem ?
try running these commands in your terminal:
composer dump-autoload // updates whatever you changed in your migration
php artisan migrate:fresh // migrates migration from the start
if these doesn't not work, post your column structure so we can understand more about your problem.
When I try to migrate tables I created I get this error
PHP Fatal error: Class 'Users' not found in /var/www/html/laravel/vendor/laravel/
framework/src/Illuminate/Database/Migrations/Migrator.php on line 301
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException",
"message":"Class 'Users' not found","file":"\/var\/www\/html\/laravel\/vendor
\/laravel\/framework\/src\/Illuminate\/Database\/Migrations\/Migrator.php",
"line":301}}
Here is my code:
Users table:
<?php
//Users Table
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->string('username');
$table->string('email');
$table->string('password');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down(){
}
}
Posts table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreatePostsTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function(Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->string('m_keyword');
$table->string('m_disc');
$table->string('slug');
$table->integer('user_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
}
}
http://laravel.io/bin/zj31n
If you get the above error while running a migration, please run the below command
composer dump-autoload
For more info,
http://laravel.com/docs/master/migrations#running-migrations
Maybe what has gone wrong is that you did not call
php artisan migrate:rollback
before
php artisan migrate
Try to force delete the tables and try to migrate again.
And another thing. The 'user_id' column in the 'posts' table should be connected to the users table like this:
Schema::table('posts', function(Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users');
});
and I would call the create the table column like this:
$table->unsignedInteger('user_id');
or
$table->integer('user_id')->unsigned();