“How to fix ‘ForeignKey’ error in Laravel” - laravel

PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1064 Yo
u have an error in your SQL syntax; check the manual that corresponds to your Ma
riaDB server version for the right syntax to use near ') on delete CASCADE' at l
ine 1")
C:\xampp\htdocs\projek\vendor\laravel\framework\src\Illuminate\Database\Connection.php:452
PDO::prepare("alter table pengerjaan add constraint pengerjaan_id_kateg
ori_foreign foreign key (id_kategori) references kategori () on delete CASC
ADE")
C:\xampp\htdocs\projek\vendor\laravel\framework\src\Illuminate\Database\Connection.php:452
public function up(){
Schema::create('pengerjaan', function (Blueprint $table) {
$table->increments('id');
$table->unsignedinteger('id_kategori');
$table->unsignedinteger('id_pelanggan');
$table->enum('status', array('proses', 'pending', 'hasil'));
$table->datetime('apply_date');
$table->timestamps();
$table->foreign('id_kategori')->refrences('id')->on('kategori')->onDelete('CASCADE');
$table->foreign('id_pelanggan')->refrences('id')->on('pelanggan')->onDelete('CASCADE');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('pengerjaan');
}

You have a spelling error, it is not refrences but it is references so change this two lines:
$table->foreign('id_kategori')->refrences('id')->on('kategori')->onDelete('CASCADE');
$table->foreign('id_pelanggan')->refrences('id')->on('pelanggan')->onDelete('CASCADE');
with this:
$table->foreign('id_kategori')->references('id')->on('kategori')->onDelete('cascade');
$table->foreign('id_pelanggan')->references('id')->on('pelanggan')->onDelete('cascade');

Related

: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails in laravel migration

In my migration file , I am adding organization id to the user's table , i tried all of the code below but not solved yet
class AddOrganizationIdToUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
// $table->foreignId('organization_id')->references('id')->on('organizations')->onDelete('cascade');
$table->foreignId('organization_id')->constrained('organizations')->cascadeOnDelete();
// $table->foreign('organization_id')->references('id')->on('organizations')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
//
});
}
I have data on my user's table so it is giving errors while migrating, to solve it I add the field as nullable
$table->foreignId('organization_id')->nullable()->references('id')->on('organizations')->onDelete('cascade');
if you write with foreignId need:
$table->foreignId('organization_id')->constrained('organizations')->cascadeOnDelete();
or just foreign
$table->foreign('organization_id')->references('id')->on('organizations')->onDelete('cascade');
What could be the issue is that this migration is running before the organizations table migration, and when it tries to find it to create the constraint it fails.
What I would suggest is on the AddOrganizationIdToUsersTable :
Schema::table('users', function (Blueprint $table) {
$table->foreignId('organization_id');
});
And on the Organization creation migration:
Schema::table('users', function(Blueprint $table) {
$table->foreign('organization_id')->references('id')->on('organizations');
});
#2 solution:
Move the migration of Organization table to run before your AddOrganizationIdToUsersTable by changing the timestamp on the name of the file

keep getting error when trying to add foreign key constraints

I have the book migration file:
<?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->increments('id');
$table->timestamps();
$table->string('title');
$table->string('Author');
$table->text('Book_description');
$table->integer('user_id');
$table->foreign('user_id')->refrences('id')->on('users');
$table->boolean('donated')->default(false);
$table->string('country',150);
$table->string('city',30);
$table->string('path');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('books');
}
}
but when I run the following command:
php artisan migrate:refresh
I get the following error:
Illuminate\Database\QueryException : SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1 (SQL: alter table books add constraint books_user_id_foreign foreign key (user_id) references users ())
I have searched Google but could not find what is wrong and also I have read Laravel 5.6 docs but I could not figure out what is wrong.
There's a typo: It has to be ->references('id') instead of ->refrences('id').
Try with this
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
});
Schema::table('books', function($table) {
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}

Dropping foreign keys in Laravel migration

I have a problem with dropping some foreign keys from my Laravel application. The problem is when I am trying to rollback the migration:
php artisan migrate:rollback
I don't know why I have errors in the console:
[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'role_user_user_id_foreign'; check that column/key exists (SQL: alter table role_user drop foreign key role_user_user_id_foreign)
[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'role_user_user_id_foreign'; check that column/key exists
[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'role_user_user_id_foreign'; check that column/key exists
Below I'm showing my migration class:
class UpdateRoleUserTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
schema::table('role_user',function(Blueprint $table){
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('role_id')->references('id')->on('roles');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('role_user', function (Blueprint $table) {
$table->dropForeign('role_user_user_id_foreign');
$table->dropForeign('role_user_role_id_foreign');
});
}
}
My table in the database has been created by migration class:
class CreateRoleUserTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('role_id')->unsigned();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
In all of the >4.0 versions of Laravel, it allows placing column names into an array, which it will then resolve on its own. I tried to find accompanying docs, but they seem to have left it out.
In your update migration, try this:
Schema::table('role_user', function (Blueprint $table) {
$table->dropForeign(['user_id']);
$table->dropForeign(['role_id']);
});
I just had this issue and the problem was due to the fact that $table->dropForeign([column_name]); drops the index and not the column itself. The solution is in the down function drop the index in one block and then drop the actual column in a separate block. They have to be dropped in separate blocks because of something to do with not being able to drop the key in the same connection as where the column is being dropped.
So the down function should look like this:
public function down() {
// drop the keys
Schema::table('role_user', function (Blueprint $table) {
$table->dropForeign(['user_id']);
$table->dropForeign(['role_id']);
});
// drop the actual columns
Schema::table('role_user', function (Blueprint $table) {
$table->dropColumn('user_id');
$table->dropColumn('role_id');
});
}
now you can run php artisan migrate to run the up function and php artisan migrate:rollback to run the down command and the error no longer shows.
I have modified your code below.
Add the onDelete() and onUpdate() to your code.
public function up()
{
Schema::table('role_user',function(Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE')->onUpdate('CASCADE');
$table->foreign('role_id')->references('id')->on('roles')->onDelete('CASCADE')->onUpdate('CASCADE');
});
}
public function down() {
Schema::table('role_user', function (Blueprint $table) {
$table->dropForeign(['user_id']);
$table->dropForeign(['role_id']);
});
}
In Laravel 9.x, you do not need to specify a separate deletion of foreign keys.
<?php
use App\Models\Question;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up(): void
{
Schema::create('answers', function (Blueprint $table) {
$table->id();
$table->foreignIdFor(Question::class, 'question_id');
$table->text('correctly');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down(): void
{
Schema::dropIfExists('answers');
}
};

Laravel:Can't drop foreign key even using 'dropForeign' method

I'm about to refresh my migration. But php artisan migrate:refresh command is not working.
It shows the following error:
[Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error
or access violation: 1091 Can't DROP 'classes_userid_foreign'; check
that column/key exists (SQL: alter table classes drop foreign key
classes_userid_foreign)
[PDOException] SQLSTATE[42000]: Syntax error or access violation:
1091 Can't DROP 'classes_userid_foreign'; check that column/key
exists
I even used the dropForeign but its not working for me.
I'm showing my migration file
public function up()
{
Schema::create('classes', function (Blueprint $table) {
$table->increments('id');
$table->integer('userId')->unsigned();
$table->string('title');
$table->string('name');
$table->string('code')->unique();
$table->integer('capacity')->unsigned();
$table->integer('tagId')->unsigned();
$table->foreign('userId')->references('id')->on('users');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('classes', function (Blueprint $table) {
$table->dropForeign(['userId']);
});
Schema::drop('classes');
}
How to fix this problem ?
Most times when you run migrations in laravel (whether up or down), and an error occurs along the line, the transaction may have completed partially without registering it in the migrations table.
If this is the case, or you will like to drop tables whether or not there really exists a foreign key, then you should consider disabling foreign key checks like so:
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::drop('classes');
Schema::enableForeignKeyConstraints();
}

Not able to add unique to products table through Laravel migration

I am trying to add unique to slug in products table and I have the following migration. However when I run php artisan migrate I get an error.
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddUniqueToProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('products', function (Blueprint $table) {
$table->unique('slug');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('products', function (Blueprint $table) {
$table->dropUnique('products_slug_unique');
});
}
}
Error
➜ php artisan migrate
[Illuminate\Database\QueryException] SQLSTATE[23000]: Integrity
constraint violation: 1062 Duplicate entry '' for key
'products_slug_unique' (SQL: alter table products add unique
products_slug_unique(slug))
[Doctrine\DBAL\Driver\PDOException] SQLSTATE[23000]: Integrity
constraint violation: 1062 Duplicate entry '' for key
'products_slug_unique'
[PDOException] SQLSTATE[23000]: Integrity constraint violation:
1062 Duplicate entry '' for key 'products_slug_unique'
What am I doing wrong here?
You can create normal field of 'slug' and create data type of slug is 'string' and you can use validator to create unique slugs, in this case you can give custom response also.
$validator = Validator::make($request->all(), [
'slug' => 'required|string|unique:products'
]);
if ($validator->fails()){
//custom response
}
Set the default for unique column to NULL before putting constraint. Since the values in slug is net to empty but not null MySql is expecting '' to be unique itself, thus preventing unique constraint on column.
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
DB::statement('UPDATE products SET slug = NULL;');
Schema::table('products', function (Blueprint $table) {
$table->unique('slug');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('products', function (Blueprint $table) {
$table->dropUnique('products_slug_unique');
});
DB::statement("UPDATE products SET slug = '';");
}
As outlined in the Migrations guide to fix this all you have to do is edit your AppServiceProvider.php file and inside the boot method set a default string length:
use Illuminate\Database\Schema\Builder;
public function boot()
{
Builder::defaultStringLength(191);
}

Resources