Laravel Contact Form Send Email Tutorial
Hi Dev,
In this tutorial, I will show you laravel contact form send email. This tutorial will give you simple example of contact us form in laravel. we will help you to give example of contact form validation in laravel. I would like to show you laravel feedback form example. Let's see bellow example contact us with send mail laravel.
You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 version.
In this example, we will create a contact us form with name, email, phone, subject, and message. we will also add form validation for the contact form. After submitting the form we will store data in the database and send an email notification to the admin email. so let's follow the below step to make this example.
Preview:
Step 1: Install Laravel
This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel example-app
Step 2: Database Configuration
In second step, we will make database configuration for example database name, username, password etc for our crud application of laravel. So let's open .env file and fill all details like as bellow:
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3: Create Migration
we are going to create contact us form. so we have to create migration for "contacts" table using Laravel 9 php artisan command, so first fire bellow command:
php artisan make:migration create_contacts_table
After this command you will find one file in following path "database/migrations" and you have to put bellow code in your migration file for create products table.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email');
$table->string('phone');
$table->string('subject');
$table->text('message');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('contacts');
}
};
Now you have to run this migration by following command:
php artisan migrate
Step 4: Create Model
In this step, we will create Contact.php model and i will create send email code on created event. so in last step we will create email class and template.
let's copy below code and paste it.
app/Models/Contact.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Mail;
use App\Mail\ContactMail;
class Contact extends Model
{
use HasFactory;
public $fillable = ['name', 'email', 'phone', 'subject', 'message'];
/**
* Write code on Method
*
* @return response()
*/
public static function boot() {
parent::boot();
static::created(function ($item) {
$adminEmail = "your_admin_email@gmail.com";
Mail::to($adminEmail)->send(new ContactMail($item));
});
}
}
Step 5: Create Routes
In this step, we will create two routes GET and POST. so let's add it.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ContactController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('contact-us', [ContactController::class, 'index']);
Route::post('contact-us', [ContactController::class, 'store'])->name('contact.us.store');
Step 6: Create Controller
In this step, we have to create new controller as ContactController and we have also need to add two methods index() and store() on that controller. We will use validation on store method. so let's update follow code:
app/Http/Controllers/ContactController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Contact;
class ContactController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
return view('contactForm');
}
/**
* Write code on Method
*
* @return response()
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email',
'phone' => 'required|digits:10|numeric',
'subject' => 'required',
'message' => 'required'
]);
Contact::create($request->all());
return redirect()->back()
->with(['success' => 'Thank you for contact us. we will contact you shortly.']);
}
}
Step 7: Create View File
In Last step, let's create contactForm.blade.php(resources/views/contactForm.blade.php) for create form with display validation message and put following code:
resources/views/contactForm.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel Contact US Form Example - ItSolutionStuff.com</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<div class="row mt-5 mb-5">
<div class="col-10 offset-1 mt-5">
<div class="card">
<div class="card-header bg-primary">
<h3 class="text-white">Laravel Contact US Form Example - ItSolutionStuff.com</h3>
</div>
<div class="card-body">
@if(Session::has('success'))
<div class="alert alert-success">
{{Session::get('success')}}
</div>
@endif
<form method="POST" action="{{ route('contact.us.store') }}" id="contactUSForm">
{{ csrf_field() }}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" class="form-control" placeholder="Name" value="{{ old('name') }}">
@if ($errors->has('name'))
<span class="text-danger">{{ $errors->first('name') }}</span>
@endif
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<strong>Email:</strong>
<input type="text" name="email" class="form-control" placeholder="Email" value="{{ old('email') }}">
@if ($errors->has('email'))
<span class="text-danger">{{ $errors->first('email') }}</span>
@endif
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<strong>Phone:</strong>
<input type="text" name="phone" class="form-control" placeholder="Phone" value="{{ old('phone') }}">
@if ($errors->has('phone'))
<span class="text-danger">{{ $errors->first('phone') }}</span>
@endif
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<strong>Subject:</strong>
<input type="text" name="subject" class="form-control" placeholder="Subject" value="{{ old('subject') }}">
@if ($errors->has('subject'))
<span class="text-danger">{{ $errors->first('subject') }}</span>
@endif
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<strong>Message:</strong>
<textarea name="message" rows="3" class="form-control">{{ old('message') }}</textarea>
@if ($errors->has('message'))
<span class="text-danger">{{ $errors->first('message') }}</span>
@endif
</div>
</div>
</div>
<div class="form-group text-center">
<button class="btn btn-success btn-submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Step 8: Create Mail Class
In this step we will create mail class ContactMail for email send on contact us form create. So let's run bellow command.
php artisan make:mail ContactMail
now, let's update code on ContactMail.php file as bellow:
app/Mail/ContactMail.php
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class ContactMail extends Mailable
{
use Queueable, SerializesModels;
public $data;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->subject('Contact US - '. $this->data->subject)
->view('emails.contact');
}
}
Here, we will create blade view file for email. In this file we will write all contact form details. now we just write some dummy text. create bellow files on "emails" folder.
resources/views/emails/contact.blade.php
<h2>Hey, It's me {{ $data->name }}</h2>
<br>
<strong>User details: </strong><br>
<strong>Name: </strong>{{ $data->name }} <br>
<strong>Email: </strong>{{ $data->email }} <br>
<strong>Phone: </strong>{{ $data->phone }} <br>
<strong>Subject: </strong>{{ $data->subject }} <br>
<strong>Message: </strong>{{ $data->user_query }} <br><br>
Thank you
next, you have to add send mail configuration with mail driver, mail host, mail port, mail username, mail password so laravel will use those sender configuration for sending email. So you can simply add as like following.
.env
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=mygoogle@gmail.com
MAIL_PASSWORD=rrnnucvnqlbsl
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=mygoogle@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
Run Laravel App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8000/contact-us
Output:
Output: You Email Look Like This
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to add Google ReCaptcha V2 in Laravel 9?
- Laravel Send an Email on Error Exceptions Tutorial
- How to Install Bootstrap in Laravel?
- Laravel Webcam Capture Image and Save from Camera Example
- Laravel 9 Barcode Generator Example
- Deploy Laravel Vapor Project with Docker Tutorial
- How to Generate Random Unique Number in Laravel?
- How to Add Custom env Variables in Laravel?
- Laravel Jetstream Login with Username or Email Example
- Laravel Carbon Subtract Minutes Example
- Laravel Carbon addYears() | Laravel Carbon Add Year Example