Home > Blockchain >  Deleting from a database Laravel9
Deleting from a database Laravel9

Time:07-07

I am trying to delete from a database in Laravel 9, My code in the blade php file is:

<form action="/waifus/{{ $waifu->id }}" method="POST">
                @csrf
                @method('DELETE')
                <button > Delete</button>
</form>

My code in the web php file is:

// Delete Waifu
Route::delete('/waifus/{waifu}', [WaifuController::class, 'delete']);

My code in the WaifuController is:

 //Delete waifu
    public function delete(Waifu $waifu)
    {
        dd($waifu);
        $waifu->delete();
        return redirect('/')->with('message', 'Waifu deleted succesfully');
    }

The problem I am facing is that, when ever I click the button inside the form, it only reloads the same page with the url: "http://localhost:8000/waifus/7?search=&_token=uE61kaZBtkCkZ4oVW8cacld3sbXaWxaJzLRixQ6X&_method=DELETE" And it doesn't go to the die dump method in the controller, any help is apricated.

Edit: Adding a new empty form like this solved my problem, but I still don't know why, can someone please explain it.

    <form>
    Delete: 
    </form>

    <form action="/waifus/{{ $waifu->id }}" method="POST">
        @csrf
        @method('DELETE')
        <button > Delete</button>
    </form>

CodePudding user response:

You cannot have nested form elements. Place your form outside the main form with a button inside that submits the delete form.

<button type="submit" form="delete_waifu" > Delete</button>

then outside of the main form

<form id="delete_waifu" action="/waifus/{{ $waifu->id }}" method="POST">
  @csrf @method('DELETE')
</form>

CodePudding user response:

you have to add button type submit like;

<button type="submit" > Delete</button>

CodePudding user response:

<form action="/waifus/{{ $waifu->id }}" method="POST">
@csrf
@method('DELETE')
<button type="submit" > Delete</button>
</form>

//Delete
public function delete($waifu)
{   
  Model::find($waifu)->delete(); // Model name will be your Model name
  return redirect('/')->with('message', 'Waifu deleted succesfully');
}

CodePudding user response:

in your controller

 //Delete waifu
public function delete($waifu)
{
    $waifu = Waifu::find($waifu)->delete(); //supposed Waifu is your Model
    return redirect('/')->with('message', 'Waifu deleted succesfully');
}
  • Related