Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Delete Product Testing

Premium
4 min read

The final part of testing the CRUD of products is, of course, the delete action.


Laravel Code

Again, first, the code for the Controller, Route, and delete button.

app/Http/Controllers/ProductController.php:

use Illuminate\Http\RedirectResponse;
 
class ProductController extends Controller
{
// ...
 
public function destroy(Product $product): RedirectResponse
{
$product->delete();
 
return redirect()->route('products.index');
}
}

routes/web.php:

use App\Http\Controllers\ProductController;
 
Route::middleware('auth')->group(function () {
Route::get('products', [ProductController::class, 'index'])->name('products.index');
 
Route::middleware('is_admin')->group(function () {
Route::get('products/create', [ProductController::class, 'create'])->name('products.create');
Route::post('products', [ProductController::class, 'store'])->name('products.store');
Route::get('products/{product}/edit', [ProductController::class, 'edit'])->name('products.edit');
Route::put('products/{product}', [ProductController::class, 'update'])->name('products.update');
Route::delete('products/{product}', [ProductController::class, 'destroy'])->name('products.destroy');
});
});

resources/views/products/index.blade.php:

// ...
@if (auth()->user()->is_admin)
<td class="px-6 py-4 whitespace-no-wrap text-sm leading-5 text-gray-900">
<a href="{{ route('products.edit', $product) }}" class="...">
Edit
</a>
<form action="{{ route('products.destroy', $product) }}" method="POST" class="inline-block">
@csrf
@method('DELETE')
<x-primary-button onclick="return confirm('Are you sure?')" class="bg-red-600 text-white">Delete</x-primary-button>
</form>
</td>
@endif
// ...

After visiting the /products URL, we now see a Delete button, which is working.

products table delete button


The Test

In the test, we will simulate the DELETE request and assert the database records.

The start of this test...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…