Can't Migrate Foreign Key - php

Here is Vehicles migrate :
public function up()
{
Schema::create('Vehicles', function (Blueprint $table) {
$table->increments('serie');
$table->string('color');
$table->integer('power');
$table->float('capacity');
$table->float('speed');
$table->integer('maker_id')->unsigned();
$table->timestamps();
});
Schema::table('Vehicles', function (Blueprint $table){
$table->foreign('maker_id')->references('id')->on('Makers');
});
}
Here is Makers Migrate :
public function up()
{
Schema::create('Makers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('phone');
$table->timestamps();
});
}
When I run artisan migrate , I got following error messages.
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table `api`.`#sql-14b0_71
` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter t
able `Vehicles` add constraint `vehicles_maker_id_foreign` foreign key (`ma
ker_id`) references `Makers` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table `api`.`#sql-14b0_71
` (errno: 150 "Foreign key constraint is incorrectly formed")
I want to create two tables: Vehicles & Makers . In vehicles , maker_id is foreign key . I read the some references for laravel migration from various sources. But I can't find solution.

Pay attention to your migration files order, you have two solutions:
Change order: make Makers Migrate file first then Vehicles Migrate.
If Makers Migrate file comes after Vehicles Migrate file and you don't want to change order, move this:
Schema::table('Vehicles', function (Blueprint $table){
$table->foreign('maker_id')->references('id')->on('Makers');
});
To Makers Migrate file.

Now I delete makers migrate file and I run vehicles migrate file . Below is vehicles migrate file.
public function up()
{
Schema::create('Vehicles', function (Blueprint $table) {
$table->increments('serie');
$table->string('color');
$table->integer('power');
$table->float('capacity');
$table->float('speed');
$table->integer('maker_id')->unsigned();
$table->timestamps();
});
}
But I got the below errors
PHP Fatal error: Cannot redeclare class CreateVehicleTable in C:\xampp\htdocs\m
yownapi\database\migrations\2016_07_05_190215_vehicles_table.php on line 35
[Symfony\Component\Debug\Exception\FatalErrorException]
Cannot redeclare class CreateVehicleTable

Now it is work properly with below codes
Makers Migrate
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class MakersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('Makers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('phone');
$table->timestamps();
});
Schema::table('Vehicles', function(Blueprint $table){
$table->foreign('maker_id')->references('id')->on('makers');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('Makers');
}
}
Vehicles Migrate
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class VehiclesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('Vehicles', function (Blueprint $table) {
$table->increments('serie');
$table->string('color');
$table->float('power');
$table->float('capacity');
$table->integer('maker_id')->unsigned();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('Vehicles');
}
}

There is a simple way to do this. From your Vehicles migration, make the following changes
public function up()
{
Schema::create('Vehicles', function (Blueprint $table) {
$table->increments('serie');
$table->string('color');
$table->integer('power');
$table->float('capacity');
$table->float('speed');
$table->integer('maker_id')
$table->foreign('maker_id')
->references('id')->on('Makers');
$table->timestamps();
});
}
And since you will be adding the values form the id column in Makers, Laravel already has got your back, so there is really no need to add the unsigned() property there. Its still Okay if you add it there.
Hope I have answered your question. For More Details

Related

Laravel Error "Illuminate\Database\QueryException" when run the 'php artisan migrate'

I can't run the "php artisan migrate" in laravel project. If I run this command then below error will display.
Migrating: 2021_08_02_173519_create_access_user
Illuminate\Database\QueryException
SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'access_id' doesn't exist in table (SQL: alter table access_user add constraint access_user_access_id_foreign foreign key (access_id) references access (id))
at C:\Users\HETTIARACHCHIGEDAMIT\LanexGloble\lanex-internal-backend\api\vendor\laravel\framework\src\Illuminate\Database\Connection.php:692
688▕ // If an exception occurs when attempting to run a query, we'll format the error
689▕ // message to include the bindings with SQL, which will make this exception a
690▕ // lot more helpful to the developer instead of just the database's errors.
691▕ catch (Exception $e) {
693▕ $query, $this->prepareBindings($bindings), $e
694▕ );
695▕ }
696▕ }
1 C:\Users\HETTIARACHCHIGEDAMIT\LanexGloble\lanex-internal-backend\api\vendor\laravel\framework\src\Illuminate\Database\Connection.php:485 \Database\Conne
PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'access_id' doesn't exist in table") in table")
2 C:\Users\HETTIARACHCHIGEDAMIT\LanexGloble\lanex-internal-backend\api\vendor\laravel\framework\src\Illuminate\Database\Conne\Database\Connection.php:485
PDOStatement::execute()
this is an error occurred file.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAccessUser extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('access_user', function (Blueprint $table) {
$table->increments('id');
$table->foreign('access_id')->references('id')->on('access');
$table->foreign('user_id')->references('id')->on('user');
$table->boolean('status');
$table->timestamp('updated_at');
$table->timestamp('created_at');
$table->string('updated_by');
$table->string('created_by');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('access_user');
}
}
You should add a column access_id before add foreign key on it. The foreign() is adding foreign key to exists column.
So, you should change migration to below:
public function up()
{
Schema::create('access_user', function (Blueprint $table) {
$table->increments('id');
// add this line
$table->unsignedBigInteger('access_id'); // depend on your foreign column type
$table->foreign('access_id')->references('id')->on('access');
$table->foreign('user_id')->references('id')->on('user');
$table->boolean('status');
$table->timestamp('updated_at');
$table->timestamp('created_at');
$table->string('updated_by');
$table->string('created_by');
});
}
or use foreignId():
public function up()
{
Schema::create('access_user', function (Blueprint $table) {
$table->increments('id');
$table->foreignId('access_id')->constrained('access'); // change here
$table->foreign('user_id')->references('id')->on('user');
$table->boolean('status');
$table->timestamp('updated_at');
$table->timestamp('created_at');
$table->string('updated_by');
$table->string('created_by');
});
}
See docs.

Laravel foreign key constraint is incorrectly formed I have searched and cannot find the answer

class CreateMediaTable extends Migration
{
public function up()
{
Schema::create('media', function (Blueprint $table) {
$table->increments('id');
$table->unsignedBigInteger('id_users');
$table->unsignedBigInteger('id_posts');
$table->char('type', 1); //P: photo or V: video
$table->string('file');
$table->timestamps();
$table->foreign('id_posts')->references('id')->on('posts');
$table->foreign('id_users')->references('id')->on('users');
});
}
public function down()
{
Schema::dropIfExists('posts');
}
}
and my createprofilemigration
/**
* #author Alex Madsen
*
* #date November 6, 2018
*/
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserProfilesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('user_profiles', function (Blueprint $table) {
$table->unsignedInteger('id_users')->unique();
$table->string('handle')->unique();
$table->string('icon')->default('https://i.redd.it/130am13nj6201.png');
$table->string('profile_image')->nullable();
$table->string('description')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('user_profiles');
}
}
Keeps throwing these errors, What am I missing? Mind you I am new to this, Trying to learn with youtube and stackoverflow on my off time. Not sure which way to go. I have looked on the forums and tried $table->foreign('id_posts')->references('id')->on('posts'); But it didn't fix the issue.
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table `ci`.`media` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter t
able `media` add constraint `media_id_posts_foreign` foreign key (`id_posts`) references `posts` (`id`))
at C:\xampp6\htdocs\lol\simple_social_network_laravel\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just the database's errors.
663| catch (Exception $e) {
> 664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| }
class CreatePostsTable extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedBigInteger('id_users');
$table->unsignedInteger('subreddit_id');
$table->text('description');
$table->string('title');
$table->text('content');
$table->unsignedInteger('id_posts');
$table->timestamps();
$table->foreign('id_users')->references('id')->on('users');
$table->foreign('subreddit_id')->references('id')->on('id_posts');
});
}
public function down()
{
Schema::dropIfExists('posts');
}
}
When using foreign keys types should be exactly the same.
You create:
$table->unsignedBigInteger('id_posts');
so it's unsigned big integer, but probably in posts table instead of bigIncrements you use just increments for id column and that's why you are getting this error.
So quite possible instead of:
$table->unsignedBigInteger('id_posts');
you should use
$table->unsignedInteger('id_posts');
or as alternative solution use
$table->bigIncrements('id');
in posts migration
In your posts migration, you made your id with increments
that is mean that it takes
unsigned integer auto_increment
but in your migration of media file, you create a posts_id with unsignedBigInteger
so there's two way to fix that choose only one
edit your id in posts migration to be bigincrements
edit your posts_id in 'media' migration to unsignedIntegere

How to add multiple columns in already made table in Laravel?

I want to add multiple number of columns in the already made table in Laravel . How can i add multiple columns ?
I don't know how to do add columns in my table. I can only add single column one at a time.
Below given is my migration table up function.
public function up()
{
Schema::create('matches', function (Blueprint $table) {
$table->increments('id');
$table->string('sports');
$table->string('match');
$table->string('date');
$table->string('time');
$table->string('teamA');
$table->longtext('teamA_flag');
$table->string('teamB');
$table->longtext('teamB_flag');
$table->string('venue');
$table->string('status');
$table->timestamps();
});
}
This is my table whose name is matches. I want to add two columns using Laravel. The name of columns are: email and qualification.
I am expecting to add multiple number of columns on the table (matches).
I want to add multiple number of columns in the already made table in Laravel . How can i add multiple columns ?
I don't know how to do add columns in my table. I can only add single column one at a time.
Create migration first by php artisan make:migration alter_table_matches,
open migration that is created by the command.
public function up()
{
Schema::table('matches', function (Blueprint $table) {
$table->string('email')->nullable()->default(null);
$table->string('qualification')->nullable()->default(null);
});
}
then in down function
public function down()
{
Schema::table('matches', function (Blueprint $table) {
$table->dropColumn('email');
$table->dropColumn('qualification');
});
}
You can just run:
php artisan make:migration add_first_item_and_second_item_and_next_item_to_matches
This creates a migration file, you can then add:
public function up()
{
Schema::table('products', function (Blueprint $table) {
$table->string('first_item');
$table->string('second_item');
$table->string('next_item');
});
}
public function down()
{
Schema::table('products', function (Blueprint $table) {
$table->dropColumn('first_item');
$table->dropColumn('second_item');
$table->dropColumn('next_item');
});
}
I hope this solves your problem
You can add new columns by creating a new migration.
Remember to make the name of the migration as descriptive as possible.
2021_09_06_083822_update_email_column_and_add_agency_id_and_contact_source_id_in_contacts_table.php
class UpdateEmailColumnAndAddAgencyIdAndContactSourceIdInContactsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('contacts', function (Blueprint $table) {
$table->string('email')->nullable();
$table->integer('agency_id')->after('country_id')->references('agentid')->on('byt_agents');
$table->foreignId('contact_source_id')->after('agency_id')->nullable()->constrained();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('contacts', function (Blueprint $table) {
$table->dropColumn(['agency_id', 'email']);
$table->dropForeign(['contact_source_id']);
});
}
}
If you want to add multiple columns to an already existing table you can follow above answer-thread
but In that case, your all columns will be added at the end of already existing columns
so, In order to add multiple columns after a certain column. You can add columns group by using callback/closure as shown in the below snippet:
class AddFieldsInMatches extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('matches', function (Blueprint $table) {
// closure to add multiple-columns after `id` column
$table->after('id', function ($table) {
$table->integer('email')->nullable();
$table->integer('qualification')->nullable();
});
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('matches', function (Blueprint $table) {
$table->dropColumn('email');
$table->dropColumn('qualification');
});
}
}
Note:
Make sure these columns must be nullable otherwise, you will get an error on running php artisan migrate command on the terminal
callback/closure approach is applicable after Laravel 8.27 versions.
Reference Article: click here
Other StackOverFlow threat: click here

A bug with renaming existing column in Laravel migrations

I added a new migration to rename an old column. Everything seems correct in this code, for me:
public function up()
{
Schema::table('reports', function (Blueprint $table) {
$table->renameColumn('reporter_id', 'created_by');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('reports', function (Blueprint $table) {
$table->renameColumn('created_by', 'reporter_id');
});
}
But then I faced an error:
In Connection.php line 664: SQLSTATE[0A000]: Feature not supported: 1846 ALGORITHM=COPY is not supported. Reason: Columns participating in a foreign key are renamed. Try ALGORITHM=INPLACE. (SQL: ALTER TABLE reports CHANGE reporter_id created_b y INT NOT NULL)
In PDOStatement.php line 140: SQLSTATE[0A000]: Feature not supported: 1846 ALGORITHM=COPY is not supported. Reason: Columns participating in a foreign key are renamed. Try ALGORITHM=INPLACE.
In PDOStatement.php line 138: SQLSTATE[0A000]: Feature not supported: 1846 ALGORITHM=COPY is not supported. Reason: Columns participating in a foreign key are renamed. Try ALGORITHM=INPLACE. `
Could you help me to fix this?
First drop koreign key on up method.
public function up()
{
Schema::table('reports', function (Blueprint $table) {
$table->dropForeign('reports_reporter_id_foreign');
$table->renameColumn('reporter_id', 'created_by');
});
}
Then add foreign key again on down method.
public function down()
{
Schema::table('reports', function (Blueprint $table) {
$table->renameColumn('created_by', 'reporter_id');
$table->foreign('reporter_id')->references('id')->on('your_related_table')->onDelete('cascade');
});
}
I've encountered this too - it makes no sense, because when I use my standard SQL client to rename the same field ... it works. But it just doesn't work as a migration script. Thus, I ended up running the RENAME inside a DB::statement and that worked for me:
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
DB::statement("ALTER TABLE `mydb`.`mytable`
CHANGE `currentfieldname` `newfieldname`
INT(10) UNSIGNED NOT NULL;");
}

Laravel empty database gives SQLSTATE[42S02] error

I'm trying to migrate my database to an empty database,
but I get the following error when I do php artisan migrate:
[Illuminate\Database\QueryException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'portal-for-fun.permissions' doesn't exist (SQL: select *
from `permissions`)
[PDOException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'portal-for-fun.permissions' doesn't exist
All migrations can be found here: https://github.com/cskiwi/portal-for-fun/tree/master/database
but I think the problem lies here:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRolesTables extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up() {
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('label')->nullable();
$table->integer('role_id')->unsigned()->nullable();
$table->timestamps();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
Schema::create('permissions', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('label')->nullable();
$table->timestamps();
});
Schema::create('permission_role', function (Blueprint $table) {
$table->integer('permission_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->primary(['permission_id', 'role_id']);
});
Schema::create('role_user', function (Blueprint $table) {
$table->integer('role_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->primary(['role_id', 'user_id']);
});
Schema::create('permission_user', function (Blueprint $table) {
$table->integer('permission_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
$table->primary(['permission_id', 'user_id']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('permission_user');
Schema::dropIfExists('role_user');
Schema::dropIfExists('permission_role');
Schema::dropIfExists('permissions');
Schema::dropIfExists('roles');
}
}
the database itself only contains an empty migration table
Create permission model in your project.
If you have permission model make sure that name in permission not Permission
I've had similar problem. Try to seaprate migrations and move part of them (those which use permissions table) from migrations folder. First, you should run migration which will create permissions table with php artisan migrate. Then move back migrations which create permission_role and permission_user tables to the migrations folder and run php artisan migrate again.
That helped me, hope it'll help you too.

Categories