Implementing Form Data Storage in Database and Email Sending
Any form on a website — feedback, application, survey — requires two things: reliable storage and prompt notification. Saving only to database risks missing submissions if email fails. Sending only to email means losing data if SMTP fails. Correct architecture makes both channels independent.
Table Structure
Minimal table for storing form submissions:
CREATE TABLE form_submissions (
id BIGSERIAL PRIMARY KEY,
form_type VARCHAR(64) NOT NULL,
payload JSONB NOT NULL,
ip INET,
user_agent TEXT,
sent_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX idx_form_submissions_form_type ON form_submissions(form_type);
CREATE INDEX idx_form_submissions_created_at ON form_submissions(created_at DESC);
payload in JSONB allows storing arbitrary structure without migrations when form changes. sent_at — timestamp of successful email send, NULL means "not sent yet" or "send failed".
Server Processing (PHP/Laravel)
// app/Http/Controllers/FormController.php
public function submit(Request $request): JsonResponse
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|max:255',
'phone' => 'nullable|string|max:32',
'message' => 'required|string|max:4000',
]);
// 1. Save to database immediately — independent of email
$submission = FormSubmission::create([
'form_type' => 'contact',
'payload' => $validated,
'ip' => $request->ip(),
'user_agent' => $request->userAgent(),
]);
// 2. Send email via queue
Mail::to(config('mail.admin_address'))
->queue(new FormSubmissionMail($submission));
return response()->json(['ok' => true]);
}
Key: ->queue() instead of ->send(). Queue means SMTP failure doesn't return 500 to user — submission is already in database, mail retries later.
Mailable
// app/Mail/FormSubmissionMail.php
class FormSubmissionMail extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
public function __construct(public FormSubmission $submission) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'New submission: ' . $this->submission->form_type,
replyTo: [
new Address($this->submission->payload['email'],
$this->submission->payload['name']),
],
);
}
public function content(): Content
{
return new Content(view: 'emails.form-submission');
}
}
replyTo is filled from user data — manager clicks "Reply" and email goes to client, not site's no-reply.
Marking Successful Send
Listener for MessageSent event updates sent_at:
// app/Listeners/MarkSubmissionSent.php
public function handle(MessageSent $event): void
{
$message = $event->message;
// extract submission_id from X-Submission-Id header
$id = $message->getHeaders()->get('X-Submission-Id')?->getValue();
if ($id) {
FormSubmission::where('id', $id)
->whereNull('sent_at')
->update(['sent_at' => now()]);
}
}
Submissions with sent_at = NULL can be periodically resent via Artisan command or viewed in admin.
Retry Failed Sends
// app/Console/Commands/RetryUnsentSubmissions.php
// Runs every 15 minutes via scheduler
$submissions = FormSubmission::whereNull('sent_at')
->where('created_at', '<', now()->subMinutes(5))
->limit(50)
->get();
foreach ($submissions as $submission) {
Mail::to(config('mail.admin_address'))
->queue(new FormSubmissionMail($submission));
}
Spam Protection
CSRF token mandatory by default in Laravel. Additionally — honeypot field and rate limiting:
Route::post('/contact', FormController::class)
->middleware(['throttle:5,1']); // 5 requests per minute per IP
For high-traffic forms — reCAPTCHA v3 or Cloudflare Turnstile (invisible).
Configuration
- Table and indexes for specific data schema
- Email template in HTML with client branding
- SMTP/Mailgun/SES setup in
.env - Supervisor for queue processing
- Submission view dashboard in admin (optional)
Basic version implementation time: 1 business day. With submission dashboard and retry logic: 2–3 days.







