Save form data to database and send to email

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1 servicesAll 2065 services
Save form data to database and send to email
Simple
~1 business day
FAQ

Our competencies:

Development stages

Latest works

  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1171
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1094
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    831
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    879
  • image_website-sbh_0.png
    Website development for SBH Partners
    999
  • image_website-_0.png
    Website development for Red Pear
    453

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.