can't delete or update item in laravel - php

when i tried delete item in laravel i get this message
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (larblog.comments, CONSTRAINT comments_article_id_foreign FOREIGN KEY (article_id) REFERENCES articles (id)) (SQL: delete from articles where id = 2)
this my delete function
public function DeleteArticle($id){
$article = Article::find($id);
$article->delete();
return redirect("article");
}
this create articles table code
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticle extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamps();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('articles');
}
}
and this create comments table code
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateComments extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->text('comment');
$table->timestamps();
$table->integer('article_id')->unsigned();
$table->foreign('article_id')->references('id')->on('articles');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('comments');
}
}
Iam tried to use this solution but did not work
$table->foreign('article_id')->references('id')->on('articles')->onUpdate('cascade')-
>onDelete('cascade');

as you know your comments depends on articles once a article is delete then comment's relation going to break so either you first delete all comment's of that artical or set foreign key null to all the comment for that article
so that why you need to update your mygration with
$table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
or
$table->integer('article_id')->unsigned()->nullable();
$table->foreign('article_id')->references('id')->on('articles')->onDelete('set null');

Related

Foreign key constraint cannot add

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table products add constraint products_brand_id_foreign foreign key (brand_id) references product_brands (id) on delete cascade)
This is my brands migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductBrandsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('product_brands', function (Blueprint $table) {
$table->id();
$table->string('brand_name');
$table->string('brand_status');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('product_brands');
}
}
and this is my products migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_name');
$table->string('sku');
$table->string('product_unit_price');
$table->string('quantity');
$table->string('product_image');
$table->string('product_description');
$table->integer('brand_id')->unsigned();
$table->integer('category_id')->unsigned();
$table->integer('unit_id')->unsigned();
$table->string('vat_type');
$table->timestamps();
});
Schema::table('products', function (Blueprint $table) {
$table->foreign('brand_id')->references('id')->on('product_brands')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('product_categories')->onDelete('cascade');
$table->foreign('unit_id')->references('id')->on('units')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}

(errno: 150 "Foreign key constraint is incorrectly formed") in laravel 9 migration

I have two tables in my laravel application.
company table
employee table.
Following is my company table migration file.
<?php
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()
{
Schema::create('companies', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('logo');
$table->text('email', 50)->unique();
$table->string('website');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('companies');
}
};
and the following is the employee table.
<?php
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()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('first_name');
$table->string('last_name');
$table->text('email', 50)->unique();
$table->text('phone', 50)->unique();
$table->integer('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('employees');
}
};
But,
Whenever I tried to run my employee table migration, it kept giving me an error saying,
SQLSTATE[HY000]: General error: 1005 Can't create table
laraapp.employees (errno: 150 "Foreign key constraint is
incorrectly formed") (SQL: alter table employees add constraint
employees_company_id_foreign foreign key (company_id) references
companies (id) on delete cascade)
ID of my company table is UNSIGNED.
The value of $table->id(); is actually unsignedBigInteger() but you've defined your company_id foreign key column to only be an unsignedInteger so the two column types do no match.
As you are using Laravel 9, you can use the foreignId() method which will automatically create the column with the correct type:
$table->foreignId('company_id');
You could also use the foreignIdFor() method which will also create the underly required fk constraint so you don't have to.
$table->foreignIdFor(Company::class);
For completeness:
<?php
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()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('first_name');
$table->string('last_name');
$table->text('email', 50)->unique();
$table->text('phone', 50)->unique();
$table->foreignIdFor(Company::class);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('employees');
}
};

Foreign key constraint is incorrectly formed issue in laravel migration

In my laravel appication I have two migrations.
2022_06_08_075452_create_schedule_types_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateScheduleTypesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('schedule_types', function (Blueprint $table) {
$table->increments('id');
$table->string('schedule_type_name');
$table->string('schedule_type_color');
$table->string('schedule_type_description');
$table->boolean('status')->default(0);
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('schedule_types');
}
}
2022_06_08_054916_create_schedules_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateSchedulesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('schedules', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('department_id');
$table->foreign('department_id')->references('id')->on('departments');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedBigInteger('company_id');
$table->foreign('company_id')->references('id')->on('companies');
$table->unsignedBigInteger('added_by');
$table->foreign('added_by')->references('id')->on('users');
$table->string('schedule_name');
$table->integer('schedule_type_id');
$table->foreign('schedule_type_id')->references('id')->on('schedule_types');
$table->date('schedule_start_date')->nullable();
$table->date('schedule_end_date')->nullable();
$table->date('schedule_actual_end_date')->nullable();
$table->time('schedule_travel_time')->nullable();
$table->unsignedBigInteger('rotation_scheme_id');
$table->foreign('rotation_scheme_id')->references('id')->on('schedule_rotational');
$table->date('rotational_schedule_period_from')->nullable();
$table->date('rotational_schedule_period_to')->nullable();
$table->unsignedBigInteger('rotation_shift_id');
$table->foreign('rotation_shift_id')->references('id')->on('schedule_has_shift');
$table->timestamps();
$table->softDeletes();
$table->index([
'department_id', 'user_id', 'schedule_type_id', 'company_id', 'added_by','schedule_start_date',
'schedule_end_date', 'rotation_scheme_id', 'rotational_schedule_period_from', 'rotational_schedule_period_to',
'rotation_shift_id']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('schedules');
}
}
But, wen I tried to run my migrations, I'm getting following error,
SQLSTATE[HY000]: General error: 1005 Can't create table
hrapp_dev.schedules (errno: 150 "Foreign key constraint is
incorrectly formed") (SQL: alter table schedules add constraint
schedules_schedule_type_id_foreign foreign key (schedule_type_id)
references schedule_types (id))
I initially thought this is occurring due to an int and bigint issue, but both are in int....
UPDATE
I ran the two migration files one at a time due to timestamp issue, but still getting the same issue...
Your foreign key schedule_type_id should be unsigned for the relationship to work. In your 2022_06_08_054916_create_schedules_table.php change to:
$table->integer('schedule_type_id')->unsigned();
Do it this way following the more cleaner syntax from Laravel 7.x:
class CreateSchedulesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('schedules', function (Blueprint $table) {
$table->bigIncrements('id');
$table->foreignId('department_id')->constrained();
$table->foreignId('user_id')->constrained();
$table->foreignId('company_id')->constrained();
$table->foreignOd('added_by')->constrained('users');
$table->string('schedule_name');
// Here is your problem the schedule_type_id was not correctly formed
$table->foreignId('schedule_type_id')->constrained();
$table->date('schedule_start_date')->nullable();
$table->date('schedule_end_date')->nullable();
$table->date('schedule_actual_end_date')->nullable();
$table->time('schedule_travel_time')->nullable();
$table->foreignId('rotation_scheme_id')->constrained('schedule_rotational');
$table->date('rotational_schedule_period_from')->nullable();
$table->date('rotational_schedule_period_to')->nullable();
$table->foreignId('rotation_shift_id')->constrained('schedule_has_shift');
$table->timestamps();
$table->softDeletes();
$table->index([
'department_id', 'user_id', 'schedule_type_id', 'company_id', 'added_by','schedule_start_date',
'schedule_end_date', 'rotation_scheme_id', 'rotational_schedule_period_from', 'rotational_schedule_period_to',
'rotation_shift_id']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('schedules');
}
}
the foreignId('tablename_id`) creates a foreign key and constrained() will make it constrained using the column name to determine the table. If you have a different table name than the one used in column name then you can pass the table in constrained('table')

Laravel Migrations: Cannot add foreign key constraint

I am trying to add foreign key constraints to my database tables via Laravel Migrations, but I always get an error like this:
Illuminate\Database\QueryException :
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
(SQL: alter table `tasks` add constraint `tasks_task_list_id_foreign` foreign key (`task_list_id`) references `task_lists` (`id`))
The migration for the tasks table looks like this:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTasksTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->integer('task_list_id')->unsigned()->index();
$table->string('task');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('task_list_id')->references('id')->on('task_lists');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('tasks');
}
}
And that's the task_lists table:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTaskListsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('task_lists', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->string('name');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('task_lists');
}
}
I can't figure out the problem and would highly appreciate any kind of help.
Thank you in advance!
You have to check the order of your migrations. Obviously, you have to run de Users table migration before the Tasks table migration. If the problem persist, try to make something like this inside the up() method and after the (Schemma::create):
Schema::table('task_lists', function($table){
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

Laravel 5.2 Cannot add foreign key constraint

I'm having issues with the migration registering in the migrations table and I'm getting the following error when I run php artisan migrate:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key
constraint (SQL: alter table `surgeon_surgeon_specialty` add
constraint `surgeon_surgeon_specialty_surgeon_id_foreign` foreign key
(`surgeon_id`) references `surgeon` (`id`) on delete cascade)
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
Here's my files currently:
Surgeons Table Migration
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSurgeonsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('surgeons', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('surgeon_name', 30)->unique();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('surgeons');
}
}
Surgeon Specialties Table Migration
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSurgeonSpecialtiesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('surgeon_specialties', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('surgeon_specialty_name');
$table->timestamps();
$table->unique(['surgeon_specialty_name','user_id']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('surgeon_specialties');
}
}
Then I used the Laravel-5-Generators-Extended package to generate the
Surgeon Surgeon Specialty Table Migration
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSurgeonSurgeonSpecialtyPivotTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('surgeon_surgeon_specialty', function (Blueprint $table) {
$table->integer('surgeon_id')->unsigned()->index();
$table->foreign('surgeon_id')->references('id')->on('surgeon')->onDelete('cascade');
$table->integer('surgeon_specialty_id')->unsigned()->index();
$table->foreign('surgeon_specialty_id')->references('id')->on('surgeon_specialties')->onDelete('cascade');
$table->primary(['surgeon_id', 'surgeon_specialty_id']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
// Schema::drop('surgeon_specialty_surgeon');
Schema::drop('surgeon_surgeon_specialty');
}
}
But changed it to this per a friends suggestion:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSurgeonSpecialtiesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('surgeon_specialties', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('surgeon_specialty_name');
$table->timestamps();
$table->unique(['surgeon_specialty_name','user_id']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('surgeon_specialties');
}
}
The table does migrate...
...however, I am still getting the error. Any help would be much appreciated.Thanks!
I had this issue on Laravel 8. I'm not sure if it's relevant to this post or not. This happens when you create the migration for the many before the one part of one-to-many relationship. In your case I guess you created migration for items before users. Simply rename your migration files according to your relationships. Your surgeon migration date should be earlier to be created before surgeon_surgeon_specialty table.
Also I suggest to declare table name of Surgeon model:
class Surgeon extends Model {
public $table = 'surgeons';
}
This is because I see Laravel couldn't determine your table name based on your model class.

Categories