Quick Summary
Learn how to create contact form using Laravel with ease. This guide walks you through setting up the form, validating and verifying user input, handling submissions, and sending emails reliably. Discover common mistakes, best practices, and optional database storage to keep messages safe. By the end, you’ll have a secure, efficient, and user-friendly contact form ready for any Laravel project.
Table of Contents
A contact form is an essential part of any website, allowing visitors to reach out and interact with the website owner. Laravel, with its powerful features, makes it straightforward to create a contact form that can send emails and save messages to the database if needed.
In this guide, I’ll explain how the experts build a functional contact form in Laravel from scratch. Let’s begin with the prerequisites to consider before getting on with the development.
Prerequisites
Before we dive into building the contact form, make sure you have a few things ready:
- Basic Laravel Setup: Ensure you have Laravel installed. If not, install it via Composer and create a new project.
- Code Editor: Use an editor like VS Code for easy file management and syntax highlighting.
- Mail Configuration: Set up an SMTP service in your .env file. This is needed for sending emails from the form. You can use Gmail for testing or services like Mailtrap for development.
- Database Ready (Optional): If you want to save form submissions, ensure a database is set up and connected to your Laravel project.
- Familiarity with Routes and Controllers: You’ll need to create routes, controllers, and views to handle the form submission and email sending.
With these in place, you’re ready to follow the steps to create contact form using Laravel and handle submissions efficiently.
Steps to Create Contact Form Using Laravel
Building a contact page in Laravel is far easier than it seems. You follow a clear path. Create the form. Validate input. Process the Laravel submit form request. Then send the message straight to your inbox. Below are the steps that you need to follow to execute the process:

Step 1: Set Up the Laravel Project
If you haven’t set up a Laravel project yet, create one using Composer:
composer create-project laravel/laravel contact-form
Navigate to the project directory:
cd contact-form
Step 2: Configure Mail Settings
In your .env file, set up your mail configuration based on the SMTP service you’re using. For example, to use Gmail, set the following:
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your_email@gmail.com
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your_email@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
Note: Avoid using your personal email credentials in production. Use environment variables or a dedicated SMTP service like Mailtrap for testing.
Step 3: Create a Contact Form
Create a view for your contact form. Start by creating a directory and a Blade file inside resources/views:
mkdir resources/views/contact
touch resources/views/contact/form.blade.php
In form.blade.php, add the following HTML form structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form</title>
</head>
<body>
<h2>Contact Us</h2>
@if(Session::has('message'))
<p>{{ Session::get('message') }}</p>
@endif
<form action="{{ route('contact.send') }}" method="POST">
@csrf
<label for="name">Name:</label>
<input type="text" name="name" id="name" required>
<label for="email">Email:</label>
<input type="email" name="email" id="email" required>
<label for="message">Message:</label>
<textarea name="message" id="message" rows="4" required></textarea>
<button type="submit">Send Message</button>
</form>
</body>
</html>
This form captures the visitor’s name, email, and message, then submits to a route we’ll define in the next step.
Step 4: Define Routes for the Contact Form
Open routes/web.php and add routes for displaying the contact form and sending the message:
use App\Http\Controllers\ContactController;
Route::get('/contact', [ContactController::class, 'showForm'])->name('contact.form');
Route::post('/contact', [ContactController::class, 'sendMail'])->name('contact.send');
Step 5: Create the ContactController
Now, create a controller to handle form display and email sending:
php artisan make:controller ContactController
In app/Http/Controllers/ContactController.php, add the following code:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\ContactMail;
class ContactController extends Controller
{
public function showForm()
{
return view('contact.form');
}
public function sendMail(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email',
'message' => 'required'
]);
$details = [
'name' => $request->name,
'email' => $request->email,
'message' => $request->message
];
Mail::to('your_email@example.com')->send(new ContactMail($details));
return back()->with('message', 'Your message has been sent successfully!');
}
}
Explanation:
showForm: Displays the contact form.sendMail: Validates the form input and sends an email to a specified address. It also returns a success message back to the form. To automate processes like sending notifications after form submission, consider implementing Laravel events and listeners for better workflow management.
Step 6: Create the Mailable Class
Use Laravel’s make:mail command to generate a mailable class that will structure the contact email. To deliver messages more efficiently and notify users about form submissions or updates, leverage the Laravel Notification System for seamless alerts.
php artisan make:mail ContactMail
Open app/Mail/ContactMail.php and modify it as follows:
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class ContactMail extends Mailable
{
use Queueable, SerializesModels;
public $details;
/**
* Create a new message instance.
*/
public function __construct($details)
{
$this->details = $details;
}
/**
* Get the message envelope.
*/
public function envelope(): Envelope
{
return new Envelope(
subject: 'New Contact Form Message',
);
}
/**
* Get the message content definition.
*/
public function content(): Content
{
return new Content(
view: 'emails.contact',
);
}
/**
* Get the attachments for the message.
*
* @return array<int, \Illuminate\Mail\Mailables\Attachment>
*/
public function attachments(): array
{
return [];
}
}
Step 7: Create the Email Template
mkdir resources/views/emails
touch resources/views/emails/contact.blade.php
Create a new email view in resources/views/emails/contact.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form Message</title>
</head>
<body>
<h3>New Contact Form Submission</h3>
<p><strong>Name:</strong> {{ $details['name'] }}</p>
<p><strong>Email:</strong> {{ $details['email'] }}</p>
<p><strong>Message:</strong> {{ $details['message'] }}</p>
</body>
</html>
This template structures the message content with details captured in the contact form.
Step 8: Testing the Contact Form
To test the form, start your Laravel development server:
php artisan serve
Then, visit http://127.0.0.1:8000/contact to see the form in action. Fill out the form, and upon submission, Laravel will validate the input, send the email, and display a success message if everything works correctly.
Step 9: Optional – Save Contact Messages to Database
If you want to save the messages in your database, create a migration for a contacts table:
php artisan make:migration create_contacts_table
In the migration file, define the table structure:
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email');
$table->text('message');
$table->timestamps();
});
Run the migration:
php artisan migrate
Create a model for a contacts table:
php artisan make:model Contact
Open app/Models/Contact.php and modify it as follows:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'message'
];
}
Now, update the sendMail function in ContactController to save the data before sending the email:
use App\Models\Contact;
public function sendMail(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email',
'message' => 'required'
]);
Contact::create($request->all());
$details = [
'name' => $request->name,
'email' => $request->email,
'message' => $request->message
];
Mail::to('your_email@example.com')->send(new ContactMail($details));
return back()->with('message', 'Your message has been sent successfully!');
}
This saves the form input to the contacts table, allowing you to keep a record of each submission.
If you need help with implementing this process for your Laravel website, get our professional Laravel development services.
How to Collect Data from a Laravel Contact Form?
Collecting form data in Laravel follows a clean and straightforward process. Each part has a purpose, and together they make your form work smoothly.
- User Fills the Form: Your visitor enters their Name, Email, and Message. Then they click “Send.”
- Form Sends Data to a Route: The Laravel contact form action points to a route. This route decides where the form data goes next.
- Controller Receives the Data: The controller handles the Laravel submit form request. It collects the details using the Request object.
- Validate the Input: Check if the fields have correct values. Stop junk, errors, and spam before they reach your system.
- Use the Data: Now you can store the message in a database, or make your Laravel contact form send email to your inbox. You choose the final action.
Simply put, collecting data from a Laravel contact form is simple and organized: the user submits the form, the controller receives and validates the input, and then you can store it or send it via email. This ensures smooth, secure, and reliable handling of all messages.
How to Validate and Verify Data from a Contact Form?
Validating data is a critical step in any Laravel contact form. It ensures the information you collect is accurate, complete, and safe. Laravel makes this process clean and simple.
- Use Laravel’s Validation Rules: Laravel provides built-in rules to check fields. For example, ensure Email is valid, Name is not empty, and Message meets a minimum length. Add rules directly in your controller when handling the Laravel form submit request.
- Stop Invalid Input Early: If a user enters incorrect or missing information, Laravel automatically rejects it. This protects your system from spam, errors, and malformed data.
- Give Clear Feedback: Show concise error messages to users. Let them know exactly which field needs fixing. This improves the user experience and increases successful submissions.
- Optional Verification: For sensitive forms, you can verify email addresses or implement captcha checks. This extra step ensures the data comes from real users, not bots.
- Clean and Ready Data: Once validation passes, the data is safe to store or use in your Laravel contact form send email action. You can trust the information you collect.
In short, validating and verifying data in a Laravel contact form ensures accuracy, completeness, and security. Use Laravel’s built-in rules to check each field, stop invalid input early, give clear error messages, and optionally verify emails or use captcha. Once validated, the data is clean and ready for storage or to send email confidently.
Common Laravel Contact Form Mistakes and How to Fix Them
Even the best Laravel contact forms can have issues. Below are the most common mistakes and how to fix them:
- Skipping Validation: Not validating input leads to spam, errors, and broken emails. The fix is to always use Laravel’s validation rules to check every field before submission.
- Misconfigured Mail Settings: Incorrect SMTP setup prevents emails from sending. The fix is to double-check your .env mail settings and test with services like Mailtrap.
- Ignoring User Feedback: No error messages frustrate users. The fix is to show clear, concise messages for missing or invalid fields.
- Forgetting CSRF Protection: Without CSRF tokens, forms are vulnerable to attacks. The fix is to include @csrf in every Blade form.
- Not Logging or Saving Submissions: Lost messages mean missed opportunities. The fix is to store submissions in the database alongside sending emails.
Avoid these pitfalls to make your Laravel contact form reliable, secure, and user-friendly.
Summary
With this guide, you now have a fully functional contact form built with Laravel. You’ve learned how to validate inputs, send emails, and optionally save submissions to the database. Laravel’s flexibility and powerful email features make it an excellent choice for implementing contact forms in any web application.
But if you have any doubts regarding the topic, I recommend you consult with our Laravel developers for hire today! (PS: This link is also going to take you to a contact form.)
FAQs on How to Create Contact Form Using Laravel
How can I secure my contact form against spam and malicious submissions?
Laravel provides built-in features and packages to help you secure your contact form. You can implement CAPTCHA solutions like Google reCAPTCHA to prevent spam submissions. Additionally, Laravel’s form validation and CSRF protection help safeguard your form against various security threats.
Can I customize the design of the contact form?
Yes, you have full control over the design of your contact form. You can use Laravel’s Blade templating engine to create custom HTML and CSS for your form. This allows you to match the form’s appearance to your application’s style.
How do I handle form submissions in Laravel?
Form submissions are typically handled by creating a controller method to process the incoming data. In this method, you can perform actions such as data validation, saving the submission to the database, and sending email notifications. Laravel provides a convenient way to access form data through the Request object.
Can I connect my Laravel contact form to external apps using APIs?
Yes, you can integrate your form data with external applications using REST or GraphQL. Check our guide on create REST API using Laravel and GraphQL Server with Laravel for detailed implementation steps.
How can I document or test my Laravel API easily?
You can use Laravel Swagger Integration to generate interactive API documentation and perform automated API testing effectively.
Looking to Integrate an Advanced Contact Form in Laravel?
Let our Laravel development team help you to implement it seamlessly.


