Contact Form

MDB Vue + Laravel

Note: This documentation is for an older version of Bootstrap (v.4). A newer version is available for Bootstrap 5. We recommend migrating to the latest version of our product - Material Design for Bootstrap 5.
Go to docs v.5

Following this tutorial requires you to complete all steps from Quick start - Laravel - we will be picking up exactly where this instruction left off.
I assume that you successfully installed composer and created simple Laravel project using mdbvue preset.

Tutorial in steps:

  1. Preparation to development
  2. Creating MDB Form
  3. Submitting form with axios
  4. Creating a controller
  5. Adding a new route
  6. Setting environment variables
  7. Sending a form

Preparation for development

1. Starting a server

If you haven't done that already, start the development server with the following command:

php artisan serve

By default server will start on port 8000, so in your browser go to http://localhost:8000/.

In separate command line window run npm run watch-poll - this way all your files will be updated immediately after reloading the page.


2. CSRF Token

Now you should see the demo page rendered on your screen. In a browser console you might've noticed the following warning:

CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token

In general, Laravel generates a CSRF (cross-site request forgery) token for each active user session and use it to verify a request’s origin. Token can be stored in a meta tag in HTML document. Open resources/views/welcome.blade.php directory and add the following line between head tags:

<meta name="csrf-token" content="{{ csrf_token() }}">

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

          <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <meta name="csrf-token" content="{{ csrf_token() }}">
            <title>Laravel</title>
          </head>

          <body>
            <div id="app">
              <example-component />
            </div>
            <script type="text/javascript" src="js/app.js"></script>
          </body>

          </html>
        
        
    

Creating MDB Vue Form

An example contact form is given below:

Contact us

Do you have any questions? Please do not hesitate to contact us directly. Our team will get back to you within a matter of hours to help you.

  • San Francisco, CA 94126, USA

  • + 01 234 567 89

  • contact@mdbootstrap.com

Copy and paste the following code into your file in resources/js/components directory (i.e. ExampleComponent.vue):

        
            
      <template>
        <mdb-container class="mt-5">
          <mdb-card>
            <mdb-card-title class="mt-4 h2">Contact us</mdb-card-title>
            <mdb-card-body>
              <mdb-card-text class="pr-5 pl-5" mr-4 ml-4>Do you have any questions? Please do not hesitate to contact us
                directly. Our team will cgetback to you within a matter of hours to help you.</mdb-card-text>
              <form class="needs-validation" novalidate @submit.prevent="submitForm">
                <mdb-row>
                  <mdb-col md="8">
                    <mdb-row>
                      <mdb-col>
                        <mdb-input label="Your name" v-model="fields.name" required />
                      </mdb-col>
                      <mdb-col>
                        <mdb-input type="email" label="Your email" v-model="fields.email" required />
                      </mdb-col>
                    </mdb-row>
                    <mdb-row>
                      <mdb-col>
                        <mdb-input label="Subject" v-model="fields.subject" required />
                      </mdb-col>
                    </mdb-row>
                    <mdb-row>
                      <mdb-col>
                        <mdb-input type="textarea" label="Your message" v-model="fields.message" required />
                      </mdb-col>
                    </mdb-row>
                  </mdb-col>
                  <mdb-col md="4">
                    <mdb-row>
                      <mdb-col class="mt-4">
                        <mdb-icon icon="map-marker-alt" size="2x" />
                        <p>San Francisco, CA 94126, USA</p>
                      </mdb-col>
                    </mdb-row>
                    <mdb-row>
                      <mdb-col class="mt-4">
                        <mdb-icon icon="phone" size="2x" />
                        <p>+ 01 234 567 89</p>
                      </mdb-col>
                    </mdb-row>
                    <mdb-row>
                      <mdb-col class="mt-4">
                        <mdb-icon icon="envelope" size="2x" />
                        <p>contact@mdbootstrap.com</p>
                      </mdb-col>
                    </mdb-row>
                  </mdb-col>
                </mdb-row>
                <mdb-btn color="primary" type="submit" class="float-left">Send</mdb-btn>
              </form>
            </mdb-card-body>
          </mdb-card>
        </mdb-container>
      </template>
      
        
    
        
            
      <script>
        import {
          mdbContainer,
          mdbInput,
          mdbCard,
          mdbCardHeader,
          mdbCardTitle,
          mdbCardText,
          mdbCardBody,
          mdbIcon,
          mdbBtn,
          mdbRow,
          mdbCol
        } from "mdbvue";
        export default {
          components: {
            mdbContainer,
            mdbInput,
            mdbCard,
            mdbCardHeader,
            mdbCardTitle,
            mdbCardBody,
            mdbCardText,
            mdbIcon,
            mdbBtn,
            mdbRow,
            mdbCol
          },
          data() {
            return {
              fields: {
                name: "",
                email: "",
                subject: "",
                message: ""
              }
            };
          },
          methods: {
            submitForm(event) {
              event.target.classList.add("was-validated");
              // submit form
            }
          }
        };
      </script>
      
        
    
        
            
      <style scoped>
        .container {
          text-align: center;
        }
      </style>
      
        
    

Submit form with axios

axios is included in Laravel App by default, so installation is unnecessary - just import axios directly to your component file.

        
            
      <script>
        import axios from "axios";
      </script>
      
        
    

Next step is to create validate() method preventing user from submitting an incomplete form. Once it is done we will be using axios to send our form to a /submit route.

        
            
      <script>
        import axios from "axios";
        import {
          mdbContainer,
          mdbInput,
          mdbCard,
          mdbCardHeader,
          mdbCardTitle,
          mdbCardText,
          mdbCardBody,
          mdbIcon,
          mdbBtn,
          mdbRow,
          mdbCol
        } from "mdbvue";
        export default {
          components: {
            mdbContainer,
            mdbInput,
            mdbCard,
            mdbCardHeader,
            mdbCardTitle,
            mdbCardBody,
            mdbCardText,
            mdbIcon,
            mdbBtn,
            mdbRow,
            mdbCol
          },
          data() {
            return {
              fields: {
                name: "",
                email: "",
                subject: "",
                message: ""
              }
            };
          },
          methods: {
            validate() {
              const form = [...arguments];
              const emailRegexp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
              for (let index in form) {
                let field = form[index];
                if (field === "email" && !emailRegexp.test(this.fields[field])) {
                  return false;
                } else if (this.fields[field] === "") {
                  return false;
                }
              }
              return true;
            },
            submitForm(event) {
              event.target.classList.add("was-validated");
              if (this.validate("email", "name", "message", "subject")) {
                axios
                  .post("/submit", this.fields)
                  .then(response => {
                    alert("Message sent!");
                    this.fields = {};
                    event.target.classList.remove("was-validated");
                  })
                  .catch(error => {
                    console.log(error);
                  });
              }
            }
          }
        };
      </script>
      
        
    

Once the message is successfully sent, we will alert the user and clear the form's inputs with this.fields = {}; line.


Create a Controller

In your command line run following command:

php artisan make:controller FormController

This will create a FormController.php file in app/Http/Controllers directory.

In the FormController class create public submit function and validate data from a request as shown below:

        
            
        <?php
          namespace App\Http\Controllers;
  
          use Illuminate\Http\Request;
  
          class FormController extends Controller
          {
            public function submit(Request $request) {
              $this->validate($request, [
                'name' => 'required|string',
                'email' => 'required|email',
                'message' => 'required',
                'subject' => 'required'
              ]);
              /*
                Mail functionality
  
              */
              return response()->json(null, 200);
            }
          }
      
        
        
    

Add a Route

To run a submit function from FormController on post request to /submit, we need to define a new route in the routes/web.php file:

        
            
          <?php
          /*
          |--------------------------------------------------------------------------
          | 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('/', function () {
            return view('welcome');
          });
          Route::post('/submit', 'FormController@submit');
    
        
        
    

Set environment variables

Laravel uses SwiftMailer library for sending emails - if you're interested in exploring more options, see offical documentation. To get started with sending emails, you need to connect the Laravel App with your Gmail account. Open .env file and set the following environment variables:

        
            
                MAIL_DRIVER =smtp
                MAIL_HOST =smtp.gmail.com
                MAIL_PORT =587
                MAIL_USERNAME=YOUR_GMAIL_USERNAME
                MAIL_PASSWORD=YOUR_GMAIL_PASSWORD
                MAIL_ENCRYPTION=tls
            
        
    

Note!

By default Gmail will block all attempts to send emails from unsafe apps - solving this issue requires opening Gmail settings and allowing access for less safe applications.


Sending email

Let's go back to our FormController.php file and complete the last step - defining email-sending functionality.

        
            
        <?php
          namespace App\Http\Controllers;
          use Illuminate\Http\Request;
          use Mail;
          use App\Http\Requests;
          use App\Http\Controllers\Controller;
          class FormController extends Controller
          {
            public function submit(Request $request) {
              $this->validate($request, [
                  'name' => 'required|string',
                  'email' => 'required|email',
                  'message' => 'required',
                  'subject' => 'required'
              ]);
              $name=$request['name'];
              $email=$request['email'];
              $title=$request['subject'];
              $message=$request['message'];
              $data = array('name'=>"Virat Gandhi");
    
              Mail::raw($message, function($message) use ($title, $name, $email){
                  $message->to(YOUR_EMAIL, YOUR_NAME)->subject
                      ($title);
                  $message->from($email, $name);
              });
              echo "Your email has been send!";
              return response()->json(null, 200);
            }
          }
        
        
    

In code above replace YOUR_EMAIL and YOUR_NAME with your data.

Now you can go back to your application and try sending an email. Explore and modify the form and logic according to your needs.

Happy coding!