'Laravel 8 Cannot delete or update a parent row: a foreign key constraint fails
For some reason a user cannot delete a Loan request if it has a bid placed on it, it was working before but when I linked loan requst with bidding on them. I have been getting this error, I can't even delete it in phpmyadmin (mysql), unless I delete the bids associated with the loan request.
Error.
Illuminate\Database\QueryException SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (
holdings.bids, CONSTRAINTbids_loan_id_foreignFOREIGN KEY (loan_id) REFERENCESloan_request(id)) (SQL: delete fromloan_requestwhereid= 4)
my Schemas;
Loan_request
Schema::create('loan_request', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('users_id');
$table->integer('LoanType');
$table->Biginteger('amount');
$table->string('PayType');
$table->integer('IntervalPay');
$table->string('GracePeriod');
$table->timestamps();
$table->foreign('users_id')
->references('id')->on('users')->ondelete('cascade');
});
my Bids schema
Schema::create('bids', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('loan_id');
$table->unsignedBigInteger('user_id');
$table->decimal('interest');
$table->string('PayType');
$table->integer('IntervalPay');
$table->string('GracePeriod');
$table->timestamps();
$table->foreign('user_id')
->references('id')->on('users')->ondelete('cascade');
$table->foreign('loan_id')
->references('id')->on('loan_request')->ondelete('cascade');
});
And the responsible Controller; Loancontroller
function delete($id)
{
Loan_requests::find($id)->delete();
session()->flash('status','Loan Request deleted successfully');
return redirect('beg');
}
config/database.php
'connections' => [
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
]
],
Solution 1:[1]
first, delete from bid table
bids::where('bids.loan_id', $id)->delete();
After that
Loan_requests::find($id)->delete();
session()->flash('status','Loan Request deleted successfully');
return redirect()->back();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hossein Azad |
