I’m trying to delete data in my Laravel project, but when I click on the Delete menu, it just shows the confirmation alert. After I click OK, it only refreshes the /barang
page, which shows the records list in the barang
table. And the item I wanted to delete is still there. What am I doing wrong?
routes/web.php
:
Route::get('/barang', [BarangController::class, 'index']);
Route::get('/barang/create', [BarangController::class, 'create']);
Route::post('/barang/create', [BarangController::class, 'store']);
Route::get('/barang/{barang:slug}/edit', [BarangController::class, 'edit']);
Route::put('/barang/{barang:slug}/edit', [BarangController::class, 'update']);
Route::delete('/barang/{barang:slug}', [BarangController::class, 'destroy']);
BarangController.php
:
public function destroy(Barang $barang)
{
Barang::destroy($barang->id);
return redirect('/barang')->with('barangSuccess', 'Data Barang berhasil dihapus');
}
views/barang/index.blade.php
:
<ul class="dropdown-menu">
<li>
<form action="/barang/{{ $row->slug }}" method="POST">
@method('delete')
@csrf
<a class="dropdown-item" href=""
onclick="return confirm('Data will be deleted. Continue?')">
<i class="bi bi-trash"></i> Hapus
</a>
</form>
</li>
</ul>
2
Answers
In your form action, make sure you are using the correct URL. You need to include the actual id of the barang item in the URL.
<form action="/barang/{{ $row->slug }}" method="POST">
Replace this line with:
This ensures that the form action points to the correct URL with the ‘id’ parameter.
Confirmation Dialog:
Ensure that the confirmation dialog properly triggers the form submission. You can use the submit method to trigger the form submission programmatically.
Maybe this can help you
Controller
With this validation, you can ensure that the barang data you want to delete actually exists in the database. If the data does not exist, an error message will be displayed.
View