Laravel 5.2 Foreign Key fails - php

I am trying to add a foreign key in my posts table to reference the id in the users table. Here are my migrations, the users table is the default one packed with laravel so the timestamps are from NOV 2014 however the posts is one I created. Any help greatly appreciated.
Thanks a lot :)
Users migration
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('name')->unique();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
posts migration
<?php
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')->unsigned();
$table->string('title');
$table->string('section');
$table->string('body');
$table->date('post_created_date');
$table->integer('author_id')->unsigned()->after('id');
$table->foreign('author_id')->references('id')->on('users');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('posts');
}
}
Every time I migrate I get the following error:

If you are creating a table, you don't want to use after as it will create a syntax error. Just place the column where you want it. I believe after will only work for alter table statements.
Schema::create('posts', function (Blueprint $table) {
$table->increments('id'); // Unsigned is assumed for increments so I removed that as well
$table->integer('author_id')->unsigned();
$table->string('title');
$table->string('section');
$table->string('body');
$table->date('post_created_date');
$table->timestamps();
$table->foreign('author_id')->references('id')->on('users');
});
Then in your model, you'd setup the relationship to your users table like so...
public function author()
{
return $this->belongsTo(User::class, 'author_id');
}
Feel free to rename the function however you want, I usually prefer to name it something that matches the foreign key.
Then you'd use it like $post->author->name.

In your CreatePostsTable class, can you try this ?
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('author_id')->unsigned();
$table->string('title');
$table->string('section');
$table->string('body');
$table->date('post_created_date');
$table->timestamps();
});
Schema::table('posts', function($table) {
$table->foreign('author_id')->references('id')->on('users');
});
}

Related

How to create composite key in Laravel?

I tried many ways but nothing work. I need to add a composite key to my table daily_deals_products. Which is developed in laravel and mysql.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateDailyDealsProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('daily__deals__products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('product_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('daily__deals__products');
}
}
Schema::create("daily__deals__products", function($table) {
$table->increments('id');
$table->integer('product_id');
$table->string('name');
});
DB::unprepared('ALTER TABLE `daily__deals__products` DROP PRIMARY KEY, ADD PRIMARY KEY ( `id` , `product_id` )');
try this :
$table->primary(['id','product_id']);
public function up()
{
Schema::create('daily__deals__products', function (Blueprint $table) {
$table->primary(['id', 'product_id']);
$table->unsignedInteger('id');
$table->foreignId('product_id')->nullable()->constrained()->onDelete('cascade');
}

Problem with error: 1215 Cannot add foreign key constraint

How to solve this error? SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table invoices add constraint invoices_form_id_foreign foreign key (form_id) references forms (id) on delete cascade)
I get it after: php artisan migrate:fresh
For foreign keys in invoices get this error. 3 foreign keys generate error but one for user_id is good and works fine. I tried all solutions and didn't worked. Please help me.
2014_10_12_000000_create_users_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
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('surname')->nullable();
$table->string('showname')->nullable();
$table->string('business')->nullable();
$table->string('NIP')->nullable();
$table->string('PESEL')->nullable();
$table->string('address')->nullable();
$table->string('city')->nullable();
$table->string('postalcode')->nullable();
$table->string('phone')->nullable();
$table->string('comments')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
2020_07_23_104440_invoices.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Invoices extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('invoices', function (Blueprint $table) {
$table->increments('id');
$table->string('invoicenumber')->nullable();
$table->date('invoicedate')->nullable();
$table->date('selldate')->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->integer('form_id')->unsigned()->nullable();
$table->integer('currency_id')->unsigned()->nullable();
$table->integer('proform_id')->unsigned()->nullable();
$table->string('paymentmethod')->nullable();
$table->date('paymentdate')->nullable();
$table->string('status')->nullable();
$table->string('comments')->nullable();
$table->string('city')->nullable();
$table->string('paid')->nullable();
$table->string('autonumber')->nullable();
$table->string('automonth')->nullable();
$table->string('autoyear')->nullable();
$table->timestamps();
});
Schema::table('invoices', function (Blueprint $table){
$table->foreign('user_id')
->references('id')
->on('users');
$table->foreign('form_id')
->references('id')
->on('forms');
$table->foreign('currency_id')
->references('id')
->on('currencys');
$table->foreign('proform_id')
->references('id')
->on('proforms');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('invoices');
}
}
2020_07_27_090356_proforms.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Proforms extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('proforms', function (Blueprint $table) {
$table->increments('id');
$table->string('proformnumber')->nullable();
$table->date('proformdate')->nullable();
$table->date('selldate')->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->string('paymentmethod')->nullable();
$table->date('paymentdate')->nullable();
$table->string('status')->nullable();
$table->string('comments')->nullable();
$table->timestamps();
});
Schema::table('proforms', function (Blueprint $table){
$table->foreign('user_id')
->references('id')
->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('proforms');
}
}
2020_07_28_091856_forms.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Forms extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('forms', function (Blueprint $table) {
$table->increments('id');
$table->string('form')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('forms');
}
}
2020_07_28_091919_currencys.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Currencys extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('currencys', function (Blueprint $table) {
$table->increments('id');
$table->string('currency')->nullable();
$table->string('course')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('currencys');
}
}
Here is what might be happening with your migrations.
1. Check the the primary and foreign key type. If user primary key ID is type $table->increments('id'); // bigInteger, then the foreign key should be bigInteger as well $table->bigInteger('user_id');
2. Please check your migration order. For example table invoices has foreign key fromforms table. During the migration, forms table should migrate first. And to make it make it happen, just rename the migration file(numeric section of file name) so that the forms.
because when excuting the migration reach this line:
$table->foreign('form_id')->references('id')->on('forms');
in 2020_07_23_104440_invoices file
the forms table has not been created yet
you should make a new migration to make that relation
Schema::table('invoices', function (Blueprint $table){
$table->foreign('form_id')
->references('id')
->on('forms');
}
this migration should be after 2020_07_28_091856_forms.php migration ...
The problem is the order of the migration
see the order
2020_07_23_104440_invoices.php
2020_07_28_091856_forms.php
when the invoices table is created there will be no forms table as it is created afterwards. So the error is because you are trying to create relationship between non existing forms table id field while creating invoices table.
What you can do is create a new migration file for attaching the relationship only.
here is how to do it
delete add foreign key from. remove this part from 2020_07_23_104440_invoices.php
$table->foreign('form_id')
->references('id')
->on('forms');
after removing create seperate migration for adding forign key
run
php artisan make:migration add_form_foreign_key_to_invoices
It will generate the new migration file. Update it like this.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddFormForeignKeyToInvoices extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('invoices', function (Blueprint $table) {
$table->foreign('form_id')->references('id')->on('forms');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('invoices', function (Blueprint $table) {
$table->dropForeign('form_id');
});
}
}

General error: 1215 Cannot add foreign key constraint in laravel

Doing the migrations I got this error:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table books add constraint books_writer_id_foreign foreign key (writer_id) references writers (id))
I've tried a lot of things but noone looks to work.
2018_02_18_3165165_create_books_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBooksTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('name');
$table->text('description');
$table->integer('numPages');
$table->enum('language', ['spanish', 'english']);
$table->date('wrote_date')->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
});
Schema::table('books', function (Blueprint $table) {
$table->integer('writer_id')->unsigned();
$table->foreign('writer_id')->references('id')->on('writers');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('books');
}
}
2018_02_18_192915_create_writers_table
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateWritersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('writers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->string('nationality');
$table->date('year_date')->nullable();
$table->date('dead_date')->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('writers');
}
}
Edit: The error was because the first migration was the books, and then the writers causing that the error.
Sometimes based on my experience too close timestamps will break the code and will throw an exception because program thinks that writers table is created after books table try to change writers_table timestamp something like: 2018_02_16_31615
Make it unsignedInteger because you're using increments()
$table->unsignedInteger('writer_id')->nullable();
change in migration source your_table_name
Schema::create('your_table_name', function (Blueprint $table) {
$table->BigIncrements('id');
to
Schema::create('your_table_name', function (Blueprint $table) {
$table->increments('id');
Move this line to the first closure:
$table->integer('writer_id')->unsigned();
Put it right after:
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
Also, you need to add timestamps to both migration files so Laravel first create the writers table and then the books table:
2018_02_01_000000_create_writers_table.php
2018_02_02_000000_create_books_table.php

Laravel 5 - Add column and foreign key to an existing table with data

I am very new at Laravel! But I'm trying. Here is were I could use some help;
I have a posts table. I have a user table. But I forgot to add a foreign key in the posts table that links to the user id.
The create users table migration:
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()
{
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');
}
}
The create posts table migration:
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->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
I have created the new migration file:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterTablePostsAddForeignUser extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
// I HAVE NO IDEA WHAT TO DO NEXT
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
}
I have no idea how to fill up the "public function up()" method here! If anyone can help! It will be much appreciated!
I tried this and this worked for me.
Schema::table('posts', function (Blueprint $table) {
$table->integer('user_id')->nullable()->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
Here When you adding foreign key, by default it will have a Null value.This 'null referencing' may cause the issue. Using nullable() foreign key will avoid that issue.
See the docs here
You need to install doctraine/dbal before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column and the you should try what I found on this SO post
Schema::table('posts', function (Blueprint $table) {
$table->integer('user_id')->unsigned()->change();
$table->foreign('user_id')->references('id')->on('users');
});
change() method for change structure of column
after this run the artisan command
php artisan migrate
if this doesn't work for you shoot the comment here! :)

Parse Error {} php Migrations

I am getting a parse error on line 50 which is the closing brace for my schema create statement however I cannot see any missing syntax so I am confused.
Code:
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('user_id');
$table->string('f_name');
$table->string('l_name');
$table->string('gender');
$table->date('dob');
$table->string('company_name');
$table->string('email')->unique();
$table->string('password');
$table->increments('landline');
$table->increments('mobile');
$table->increments('activated');
$this->increments('social_login');
$table->timestamp('last_login');
$table->rememberToken();
}
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
Schema::create(
You never closed that (.
Schema::create('users', function (Blueprint $table) {
$table->increments('user_id');
$table->string('f_name');
$table->string('l_name');
$table->string('gender');
$table->date('dob');
$table->string('company_name');
$table->string('email')->unique();
$table->string('password');
$table->increments('landline');
$table->increments('mobile');
$table->increments('activated');
$this->increments('social_login');
$table->timestamp('last_login');
$table->rememberToken();
});
You are using the increments method incorrectly - Laravel will attempt to make an auto-incrementing primary key for each of the $table->increments(...); statements. Even the fields being specified would not suggest that an auto-incrementing field would be appropriate, you should check out the available methods in the Laravel docs

Categories