I'm trying to make a delete button in Laravel, but it redirects me to a white page. this is the html code for the delete button (it's an icon):
<a class="icon" href="{{ route('capteurs.destroy', $capteur->id)}}" data-balloon="Supprimer" data-balloon-pos="right">
<i class="fe fe-trash-2" ></i>
</a>
destroy
function in the controller class:
public function destroy($id)
{
$capteur = Capteur::find($id);
$capteur->delete();
return redirect('/capteurs')->with('success', 'Capteur Supprimé');
}
I'm supposed to be redirected to /capteurs
which is this page:
Instead i get redirected here, and the element i wanna delete is still there:
Edit: Routes for capteurs
Route::resource('capteurs', 'CapteurController');
I think you should make a form for that:
<form method="POST" action="{{ route('capteurs.destroy', $capteur->id)}}"
@csrf
@method('DELETE')
<a class="icon" data-balloon="Supprimer" data-balloon-pos="right">
</a>
<button type="submit"><i class="fe fe-trash-2" ></i></button>
</form>
You're currently linking to your destroy page like its a GET request, while it should be a POST request. If execute php artisan route:list
it will show information on the routes.
To fix this:
<form action="{{ URL::route('capteurs.destroy', $capteur->id) }}" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button><i class="fe fe-trash-2" ></i></button>
</form>
You'll probably have to edit styling a bit though
You need to add a form
around your anchor tag and next thing you need is a DELETE
request instead of GET
. You can try the below code:
<form action="{{ route('capteurs.destroy', $capteur->id) }}" method="POST">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<button type='submit' class="btn btn-danger" ><i class="fe fe-trash-2" ></i></button>
</form>
If you really want it to do with the anchor tag then give a specific id
to your anchor tag and do an ajax request!