Laravel 7 Contact Form Example Tutorial

Last updated on by Digamber
Do you want to know how to create a Contact Form in Laravel 7 and store the contact form data in MySQL database then you are at the right place.

Contact Us form is a widely used feature required by almost every web or mobile application. In this Laravel contact form example tutorial, we will learn to create a contact form in Laravel using the Bootstrap 4 CSS Framework, validate contact form using Laravel built-in validation, send email to admin using Mailtrap.

Laravel Contact Form with Bootstrap

If you are a beginner in PHP, you must check out our detailed article on How to Create Contact Form in PHP with jQuery Form Validation.

Install Laravel Project

Install a new Laravel project using given below command.

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

Mode inside the project folder.

cd laravel-contact-form

Make Database Connection

Include your database configuration details in .env file to make the set up the connection between Laravel and MySQL.

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=

Create Model and Run Database Migrations

Let us create the Model for contact form, in here we define the table Schema, execute the following command. It will create a Model and migration file. We have to create the table structure by specifying the values in the migrations file and also declare those values in the Model file as a Schema.

php artisan make:model Contact -m

Open database/migrations/timestamp_create_contacts_table.php file and add the values for contact us form that we stored in the MySQL database.

<?php

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

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');
            $table->string('subject');
            $table->text('message');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('contacts');
    }
}

Add the following code in the app/Contact.php file.

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Contact extends Model {

    public $fillable = ['name', 'email', 'phone', 'subject', 'message'];

}

Next, run the migration using the below command. Once the command is completed, go to the database and check the contacts table created with a name, email, phone, subject, and message values.

php artisan migrate

Create Contact Form Controller

Execute the following command to generate the contact form controller file.

php artisan make:controller FormValidtionController

Open app/Http/Controller/ContactUsFormController.php file and add the following code in it.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Contact;


class ContactUsFormController extends Controller {

    // Create Contact Form
    public function createForm(Request $request) {
      return view('contact');
    }

    // Store Contact Form data
    public function ContactUsForm(Request $request) {

        // Form validation
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email',
            'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
            'subject'=>'required',
            'message' => 'required'
         ]);

        //  Store data in database
        Contact::create($request->all());

        // 
        return back()->with('success', 'We have received your message and would like to thank you for writing to us.');
    }

}

Import the Contact Model from the App folder.

Create two functions one for rendering contact form in view and to connect controller to form. The ContactUsForm() function is useful for storing user data in the database.

We need to define a ContactUsForm() function and pass the $request parameter to it. To validate the contact us form in Laravel, we will use the request object. This can allow us to use Laravel’s built-in validation.

Configure Contact Form Routes in Laravel

Go to routes/web.php file and define the two routes.

The first route is created with the GET method, and it renders the contact form in the view.

The Second route handles the various tasks such as form validation, storing form data in the database and displaying success message to the user on frontend.

<?php

use Illuminate\Support\Facades\Route;


// Render in view
Route::get('/contact', [
    'uses' => 'ContactUsFormController@createForm'
]);

// Post form data
Route::post('/contact', [
    'uses' => 'ContactUsFormController@ContactUsForm',
    'as' => 'contact.store'
]);

Add Custom CSS in Laravel

In this step, we will learn to add custom CSS in Laravel project. First, create /css/style.css file in public folder. Also, place the given CSS code in the newly created CSS file.

.container {
    max-width: 500px;
    margin: 50px auto;
    text-align: left;
    font-family: sans-serif;
}

form {
    border: 1px solid #1A33FF;
    background: #ecf5fc;
    padding: 40px 50px 45px;
}

.form-control:focus {
    border-color: #000;
    box-shadow: none;
}

label {
    font-weight: 600;
}

.error {
    color: red;
    font-weight: 400;
    display: block;
    padding: 6px 0;
    font-size: 14px;
}

.form-control.error {
    border-color: red;
    padding: .375rem .75rem;
}

Now, you can easily call this CSS file in the Laravel blade template, we need to paste the following code in the view/contact.blade.php file to add the custom CSS in Laravel.

<link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">

Create Laravel 7 Contact Form with Bootstrap

Go to resources/views/ folder and create contact.blade.php file inside of it. Then, add the following code in it.

We created a beautiful contact form using Bootstrap CSS Framework. The @csrf tag protects contact form from CROSS Site Request Forgery.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">
</head>

<body>
    <div class="container mt-5">

        <!-- Success message -->
        @if(Session::has('success'))
            <div class="alert alert-success">
                {{Session::get('success')}}
            </div>
        @endif

        <form action="" method="post" action="{{ route('contact.store') }}">

            <!-- CROSS Site Request Forgery Protection -->
            @csrf

            <div class="form-group">
                <label>Name</label>
                <input type="text" class="form-control" name="name" id="name">
            </div>

            <div class="form-group">
                <label>Email</label>
                <input type="email" class="form-control" name="email" id="email">
            </div>

            <div class="form-group">
                <label>Phone</label>
                <input type="text" class="form-control" name="phone" id="phone">
            </div>

            <div class="form-group">
                <label>Subject</label>
                <input type="text" class="form-control" name="subject" id="subject">
            </div>

            <div class="form-group">
                <label>Message</label>
                <textarea class="form-control" name="message" id="message" rows="4"></textarea>
            </div>

            <input type="submit" name="send" value="Submit" class="btn btn-dark btn-block">
        </form>
    </div>
</body>

</html>

Laravel Contact Form Validation

We are validating a contact form and accessing the errors for each form input field using $errors->has() method.

<form action="" method="post" action="{{ route('contact.store') }}">

    @csrf

    <div class="form-group">
        <label>Name</label>
        <input type="text" class="form-control {{ $errors->has('name') ? 'error' : '' }}" name="name" id="name">

        <!-- Error -->
        @if ($errors->has('name'))
        <div class="error">
            {{ $errors->first('name') }}
        </div>
        @endif
    </div>

    <div class="form-group">
        <label>Email</label>
        <input type="email" class="form-control {{ $errors->has('email') ? 'error' : '' }}" name="email" id="email">

        @if ($errors->has('email'))
        <div class="error">
            {{ $errors->first('email') }}
        </div>
        @endif
    </div>

    <div class="form-group">
        <label>Phone</label>
        <input type="text" class="form-control {{ $errors->has('phone') ? 'error' : '' }}" name="phone" id="phone">

        @if ($errors->has('phone'))
        <div class="error">
            {{ $errors->first('phone') }}
        </div>
        @endif
    </div>

    <div class="form-group">
        <label>Subject</label>
        <input type="text" class="form-control {{ $errors->has('subject') ? 'error' : '' }}" name="subject"
            id="subject">

        @if ($errors->has('subject'))
        <div class="error">
            {{ $errors->first('subject') }}
        </div>
        @endif
    </div>

    <div class="form-group">
        <label>Message</label>
        <textarea class="form-control {{ $errors->has('message') ? 'error' : '' }}" name="message" id="message"
            rows="4"></textarea>

        @if ($errors->has('message'))
        <div class="error">
            {{ $errors->first('message') }}
        </div>
        @endif
    </div>

    <input type="submit" name="send" value="Submit" class="btn btn-dark btn-block">
</form>

Set Up Laravel Email Template

Create resources/views/mail.blade.php file and add the given below code in it. We will add the contact form values which is sent by site visitor in this template, and you will see these values in your mailbox.

<h2>Hello</h2> <br><br>

You have got an email from : {{ $name }} <br><br>

User details: <br><br>

Name: {{ $name }} <br>
Email: {{ $email }} <br>
Phone: {{ $phone }} <br>
Subject: {{ $subject }} <br>
Message: {{ $user_query }} <br><br>

Thanks

Configure Laravel Email Server with Mailtrap

There are tons of other methods to set up mail a server in Laravel, but we are going to configure Email server in Laravel using Mailtrap.

Create an account with Mailtrap, Click on settings icon, copy your username and password from SMTP Settings tab.

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_mailtrap_username
MAIL_PASSWORD=your_mailtrap_password
MAIL_ENCRYPTION=tls

Sending Email in Laravel

Execute the below command to setup the Laravel’s basic email function. Following command will create a new Mailable class with contact.php file inside the app/Mails/ directory.

php artisan make:mail contact

Again, go to Http/Controllers/ContactUsFormController.php file and replace the entire code with the given below code.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Contact;
use Mail;

class ContactUsFormController extends Controller {

    // Create Contact Form
    public function createForm(Request $request) {
      return view('contact');
    }

    // Store Contact Form data
    public function ContactUsForm(Request $request) {

        // Form validation
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email',
            'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
            'subject'=>'required',
            'message' => 'required'
         ]);

        //  Store data in database
        Contact::create($request->all());

        //  Send mail to admin
        \Mail::send('mail', array(
            'name' => $request->get('name'),
            'email' => $request->get('email'),
            'phone' => $request->get('phone'),
            'subject' => $request->get('subject'),
            'user_query' => $request->get('message'),
        ), function($message) use ($request){
            $message->from($request->email);
            $message->to('digambersingh126@gmail.com', 'Admin')->subject($request->get('subject'));
        });

        return back()->with('success', 'We have received your message and would like to thank you for writing to us.');
    }

}

Your contact form is up and running. You can store the user data in the MySQL database and send email to the provided email address.

Start the application using the following command.

php artisan serve

Click on the URL to test the Contact Form application in Laravel:

http://127.0.0.1:8000/contact

Laravel 7 Contact Form

Conclusion

So, this was it. In this article, we have understood how to create a Contact Form in Laravel, set up an email server with Mailtrap.io, and send an email to Admin from Laravel application.

Thanks for reading, you can get the full code of this tutorial on GitHub.