Laravel 11 Contact Form with Email Sending Tutorial

Throughout this Laravel 11 Contact Form with Email Sending Tutorial, you will learn how to create a contact form in Laravel 11 and send emails step-by-step. We’ll cover setting up a contact us page in Laravel, including form validation and storing data in a MySQL database, along with sending email notifications.

Contact Us in Laravel 11 with Send Email Example

Use to follow the step by step guide on how to integrate the contact us form with send email in Laravel.

  • Download Laravel App
  • Setup Database Credentials
  • Generate Model And Migration
  • Create Routes for Contact Us form in Laravel
  • Create Controller
  • Create Contact Us Blade File
  • Create Email Send Blade File
  • Configuring Email server
  • Laravel Contact Send Email Example
  • Run development server

#1 Download Laravel 11 App

First, you need to download a new Laravel 11 application using the following command;

composer create-project --prefer-dist laravel/laravel laravel-contact-form

Next, go inside the app:

cd laravel-contact-form

#2 Setup Database Credentials

Next, open the .env file and update the database credentials on it;

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

#3 Make Model & Migration File

Now in this step you need to generate the Contact model and migration file using the following command.

php artisan make:model Contact -m

Now, open the database/migrations/2023_04_20_161223_create_contacts_table.php file and update the below code on it.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateContactsTable 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_number')->nullable();
            $table->string('subject')->nullable();
            $table->text('message')->nullable();
            $table->timestamps();
        });
    }
    
    /**
    * Reverse the migrations.
    *
    * @return void
    */
     public function down()
     {
	    Schema::drop("contacts");
     }
}

Next, run the migration using the below command. Once the command is completed, go to the database and check the contacts table you will see the tables will have name, email, phone_number, subject, and message columns.

php artisan migrate

#4 Create Routes for Contact Us form in Laravel

Next, open your routes/web.php file and add the following route. One is for showing the contact us form and the other is to save the data in the database with email send in Laravel.

<?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 and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/contacts', [ContactController::class, 'index']);
Route::post('/contacts', [ContactController::class, 'save'])->name('contacts.store');

Route::get('/', function () {
    return view('welcome');
});

#5 Create Controller

In this step, open your terminal and execute the following command to create the ContactController.php file.

php artisan make:controller ContactController

Now, go to app/http/controller/ContactController.php and update the following code in your controller file.

<?php 

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Contact;
use Mail;

class ContactController extends Controller {
    
    public function index() {
        return view('contacts-us');
    }
    
    public function save(Request $request) {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email',
            'subject' => 'required',
            'phone_number' => 'required|digits:10|numeric',
            'message' => 'required'
        ]);

        Contact::create($request->all());

        return back()->with('success', 'Thank you for contact us!');
    }
}

#6: Create Contact Blade View File

Next, navigate the resources/views directory and create a new file named contact-us.blade.php. Now open the resources/views/contacts-us.blade.php and update the following code on it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="content">
            <div class="row">
                <div class="col-md-12">
                    <div class="card card-user">
                        <div class="card-header">
                            <h5 class="card-title">Contact Us</h5>
                        </div>
                        <div class="card-body">
                            @if(Session::has('success'))
                                <div class="alert alert-success">
                                {{ Session::get('success') }}
                                </div>
                            @endif

                            <form method="post" action="contact-us">
                            {{csrf_field()}}
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                        <label> Name </label>
                                        <input type="text" class="form-control @error('name') is-invalid @enderror" placeholder="Name" name="name">
                                        @error('name')
                                            <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                            </span>
                                        @enderror
                                        </div>
                                    </div>
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label> Email </label>
                                            <input type="text" class="form-control @error('email') is-invalid @enderror" placeholder="Email" name="email">
                                            @error('email')
                                                <span class="invalid-feedback" role="alert">
                                                <strong>{{ $message }}</strong>
                                                </span>
                                            @enderror
                                        </div>
                                    </div> 
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label> Phone Number </label>
                                            <input type="text" class="form-control @error('phone_number') is-invalid @enderror" placeholder="Phone Number" name="phone_number">
                                            @error('phone_number')
                                                <span class="invalid-feedback" role="alert">
                                                <strong>{{ $message }}</strong>
                                                </span>
                                            @enderror
                                        </div>
                                    </div>
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label> Subject </label>
                                            <input type="text" class="form-control @error('subject') is-invalid @enderror" placeholder="Subject" name="subject">
                                            @error('subject')
                                                <span class="invalid-feedback" role="alert">
                                                <strong>{{ $message }}</strong>
                                                </span>
                                            @enderror
                                        </div>
                                    </div>
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label> Message </label>
                                            <textarea class="form-control textarea @error('message') is-invalid @enderror" placeholder="Message" name="message"></textarea>
                                            @error('message')
                                                <span class="invalid-feedback" role="alert">
                                                <strong>{{ $message }}</strong>
                                                </span>
                                            @enderror
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="update ml-auto mr-auto">
                                        <button type="submit" class="btn btn-primary btn-round">Send</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

#7 Create Send Email Blade File

Next, you need to create another blade file contact-email.blade.php insde the resources/views directory. This file content show in your mail inbox. So open the resources/views/contact-email.blade.php file and update the mail contact on it.

<h2>Hello,</h2>
    You received an email from : {{ $name }}
Here are the details:
    <b>Name:</b> {{ $name }}
    <b>Email:</b> {{ $email }}
    <b>Phone Number:</b> {{ $phone_number }}
    <b>Subject:</b> {{ $subject }}
    <b>Message:</b> {{ $user_message }}
Thank You!!

#8 Configuring Email server

Sending email doesn’t have to be complicated. Laravel provides a clean, simple email API powered by the popular SwiftMailer library. Laravel and SwiftMailer provide drivers for sending email via SMTP, Mailgun, Postmark, Amazon SES, and sendmail, allowing you to quickly get started sending mail through a local or cloud based service of your choice.

In this step, we are going to configure the MailTrap SMTP server in Laravel. Firstly you need to create an account in mailtrap.io.

Login to your mailtrap account and go SMTP setting copy username and password details and add in your .env file just seeding below.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=587
MAIL_USERNAME=331e7######## #Your mailtrap username
MAIL_PASSWORD=25a10######## #Your mailtrap password
MAIL_ENCRYPTION=tls

#9 Laravel Contact Send Email Example

After all the configuration for the email send in Laravel, now we need to update the below code in our ContactController file. This mail function will send an email to your mailtrap account. I have updated the mail function with our controller file in the next step.

\Mail::send('contact-email',
    array(
        'name' => $request->get('name'),
        'email' => $request->get('email'),
        'subject' => $request->get('subject'),
        'phone_number' => $request->get('phone_number'),
        'user_message' => $request->get('message'),
    ), function($message) use ($request)
    {
        $message->from($request->email);
        $message->to('admin@example.com');
    });

#10 Update Controller code with Mail Function

Here is the full code of Laravel contact us form with Email send example.

<?php 

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Contact;
use Mail;

class ContactController extends Controller {
    
    public function index() {
        return view('contacts-us');
    }
    
    public function save(Request $request) {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email',
            'subject' => 'required',
            'phone_number' => 'required|digits:10|numeric',
            'message' => 'required'
        ]);

        Contact::create($request->all());

        Mail::send('contact-email',
            [
                'name' => $request->get('name'),
                'email' => $request->get('email'),
                'subject' => $request->get('subject'),
                'phone_number' => $request->get('phone_number'),
                'user_message' => $request->get('message'),
            ], function($message) use ($request)
            {
                $message->from($request->email);
                $message->to('admin@example.com');
            });
            
        return back()->with('success', 'Thank you for contact us!');
    }
}

#11 Run your App and Test

Now, its time to test our Laravel Contact Form with send email example. So start your application using the serve command.

php artisan serve

After that hit the url in your browser and test the contact us in laravel and send email.

http://localhost:8000/contacts