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 our Laravel development experts build a functional contact form in Laravel from scratch.
Prerequisites
To follow this tutorial, you need to configure a mail service like Gmail, Mailtrap, or any other SMTP provider to test email functionality. And if you don’t want to send any email just wanted to store data in your DB that also you can do.
Step 1: Setting 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.
Ready to elevate your project with our Laravel services?
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.
Step 6: Create the Mailable Class
Use Laravel’s make:mail command to generate a mailable class that will structure the contact email:
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.
Got questions about your Laravel project? Get in touch today!
FAQs on How to Create Contact Form Using Laravel
- Validating user input using Laravel's built-in form validation
- Properly configuring email settings
- Securing your form against CSRF attacks and,
- Organizing your code using Laravel's MVC structure
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 experts today! (PS: This link is also going to take you to a contact form.)