Courses

Testing in Laravel 12 For Beginners

Delete Product Testing

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Testing record deletion
- Using database assertions for deletion
- Verifying redirect after deletion
- Testing database record counts

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 25 lessons of this course? (90 min read)

You also get:

  • 76 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord