Courses

Testing in Laravel 12 For Beginners

New Product: Test that Record is Saved to DB

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Testing database record creation
- Verifying form submissions
- Using database assertions
- Testing redirect after successful creation

So far, we have been testing the getting of the data. So now, let's test if data exists in the database, after we added it from the form.


Laravel Code

First, let's create a simple form and store the product in the database.

We will use Form Request for the validation.

php artisan make:request StoreProductRequest

app/Http/Requests/StoreProductRequest.php:

class StoreProductRequest extends FormRequest
{
public function rules(): array
{
return [
'name' => 'required',
'price' => 'required',
];
}
 
public function authorize(): bool
{
return true;
}
}

app/Http/Controllers/ProductController.php:

use App\Models\Product;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use App\Http\Requests\StoreProductRequest;
 
class ProductController extends Controller
{
// ...
 
public function create(): View
{
return view('products.create');
}
 
public function store(StoreProductRequest $request): RedirectResponse
{
Product::create($request->validated());
 
return redirect()->route('products.index');
}
}

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

<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Create product') }}
</h2>
</x-slot>
 
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<div class="overflow-hidden overflow-x-auto p-6 bg-white border-b border-gray-200">
<div class="min-w-full align-middle">
<form method="POST" action="{{ route('products.store') }}">
@csrf
 
<div>
<x-input-label for="name" :value="__('Name')" />
<x-text-input id="name" class="block mt-1 w-full" type="text" name="name" :value="old('name')" required autofocus />
<x-input-error :messages="$errors->get('name')" class="mt-2" />
</div>
 
<div class="mt-4">
<x-input-label for="price" :value="__('Price')" />
<x-text-input id="price" class="block mt-1 w-full" type="text" name="price" :value="old('price')" required />
<x-input-error :messages="$errors->get('price')" class="mt-2" />
</div>
 
<div class="flex items-center mt-4">
<x-primary-button>
{{ __('Save') }}
</x-primary-button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</x-app-layout>

After visiting the create product, we see a form and can save a new product.

products create form


The Tests

Now let's add tests that the creation of the product works and the record is found in the database.

In the test, first, we make...

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