Laravel Contact Form Send Email Tutorial

In this tutorial, we’ll be discussing various steps to create a Laravel contact form and send emails. This tutorial will provide you simple example of the contact us form in Laravel. This example can be used with Laravel 6, Laravel 7, Laravel 8, and Laravel 9 versions.

Let’s 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 is submitted, we’ll be storing the data in the database and then sending an email notification to the admin email.

contact us laravel

Step 1: Install Laravel

In case you have not created the laravel app, then you may use the below command.

composer create-project laravel/laravel example-app

Step 2: Database Configuration

Make database configuration like the database name, username, password, etc for our crud application of laravel. Open the  .env file and fill in all the details below:

.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 a Migration

Let’s create migration for the “contacts” table with the help of the Laravel 9 PHP artisan command, so use the below command:

php artisan make:migration create_contacts_table

After using this command, you will see one file in the following path “database/migrations” and you have to enter the below code in your migration file to create a 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');
    }
};

Run this migration by following the command:

php artisan migrate

Step 4: Create a Model

Create a Contact.php model and send the email code to the created event. In the last step, we will create an email class and template.

let’s use the below code.

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 = "[email protected]";
            Mail::to($adminEmail)->send(new ContactMail($item));
        });
    }
}

Step 5: Create Routes

Creating two routes GET and POST. So, we’ll 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

We’ll create a new controller as ContactController and we’ll also be adding two methods index() and store() on that controller. Validation is used on store method. Use the below 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

Let’s create contactForm.blade.php (resources/views/contactForm.blade.php) to create a form that displays a validation message and use the following code:

resources/views/contactForm.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Contact US Form Example</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-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

We’ll be creating a mail class ContactMail for emails sent on the contact us form. Run the below command.

php artisan make:mail ContactMail

Update the below code on the ContactMail.php file as below:

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');
    }
}

Create a blade view file for email. In this file, we will be writing all contact form details. Let’s write some dummy text. Create the below files in the “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>

Now, add send mail configuration with mail driver, mail host, mail port, mail username, and mail password, so Laravel will be using those sender configurations for sending the email. Add the below code:

.env
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=rrnnucvnqlbsl
MAIL_ENCRYPTION=tls
[email protected]
MAIL_FROM_NAME="${APP_NAME}"

Run Laravel App

Now, Type the given below command and press “enter” to run the Laravel app:

php artisan serve

Now, visit your web browser, type the given URL and view the app output:

contact us laravel

Notice: ob_end_flush(): failed to send buffer of zlib output compression (1) in /home/u212091429/domains/mydevhelp.com/public_html/wp-includes/functions.php on line 5420

Notice: ob_end_flush(): failed to send buffer of zlib output compression (1) in /home/u212091429/domains/mydevhelp.com/public_html/wp-includes/functions.php on line 5420