0

I am removing a wine shop from my project; a wine is associated with this wine shop that I am eliminating (relationship Many to Many).

When I click Delete I get this error:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (dbfullexercise.wine_wineshop, CONSTRAINT wine_wineshop_wineshop_id_foreign FOREIGN KEY (wineshop_id) REFERENCES wineshops (id))

What should I do to remove this error? I looked at the documentation but found nothing about it.

I'm new to Laravel

Pivot table creation for Many to Many relationship:

<?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('wine_wineshop', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('wine_id');
            $table->foreign('wine_id')->references('id')->on('wines');
            $table->unsignedBigInteger('wineshop_id');
            $table->foreign('wineshop_id')->references('id')->on('wineshops')->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('wine_wineshop');
    }
};

WineshopController.php

public function destroy(Wineshop $wineshop)
{
    //dd($wineshop);

    $wineshop->delete();
    return redirect(route('wineshop.index'));
}

show.blade.php

<form action="{{route('wineshop.destroy', compact('wineshop'))}}" method="post">
    @method('delete')
    @csrf
    <button type="submit" class="btn btn-danger">Elimina enoteca</button>
</form>
Peppermintology
  • 9,343
  • 3
  • 27
  • 51
Aurora
  • 5
  • 5
  • Does this answer your question? [Laravel onDelete cascade many-to-many relationship](https://stackoverflow.com/questions/48344236/laravel-ondelete-cascade-many-to-many-relationship) – Waqas Altaf Jul 18 '22 at 09:34
  • Already seen but does not answer my question – Aurora Jul 18 '22 at 09:43
  • There are some [conditions and restrictions](https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html) for the cascade to work, one being the engine used should be `InnoDB` on all tables involved. – Peppermintology Jul 18 '22 at 10:10
  • I did it; it simply lacked the detach in the destroy() function that I missed putting it. – Aurora Jul 18 '22 at 10:51

0 Answers0