Contact Us Form in Laravel



Hello, friends today we are going to create a custom contact page in Laravel 5.7. In this tutorial, you will see how to create a contact us form that will not only save the visitors details in your MySQL database as well also send an email to website admin.

Create a Contact Form in Laravel 5.7 Tutorial


  1. Installing Laravel 5.7
  2. Configuring Mysql Database with Laravel 5.7
  3. Creating and running Database migration in Laravel 5.7 for Contact us table.
  4. Creating our Model
  5. Creating Routes for contact us page
  6. Creating our Controller
  7. Creating View file for Contact us page.
  8. Creating Email template in Laravel.
  9. Configuring an Email server.
  10. Sending Email to Admin
  11. Conclusion


1. Installing Laravel 5.7

Open your command prompt or your terminal and run below commands to install and configure Laravel Framework
cd to your server directory and run composer create-project command to create a new Laravel project. It will take a few minutes to install the framework.

composer create-project laravel/laravel contactUs --prefer-dist
Once the installation is completed go into the project folder

cd contactUs 


2. Configuring the Mysql Database with Laravel 5.7

Open .env file and replace DB_HOST,DB_DATABASE,DB_USERNAME,DB_PASSWORD to yours

DB_CONNECTION=mysql
DB_HOST=127.0.0.1 // your host
DB_PORT=3306
DB_DATABASE=homestead // your database name
DB_USERNAME=homestead // your database username
DB_PASSWORD=secret // your database username

3. Creating and running Database migration in Laravel 5.7

Run below command to create migration file for 'contact_us' table.

php artisan make:migration create_contact_us_table
Running above command will create a migration file in your database/migrations directory named something like 2018_09_19_122633_create_contact_us_table.php . Open that file add following code in it.

<?php
   use Illuminate\Support\Facades\Schema;
   use Illuminate\Database\Schema\Blueprint;
   use Illuminate\Database\Migrations\Migration;
   class CreateContactUsTable extends Migration
   {
       /**
        * Run the migrations.
        *
        * @return void
        */
       public function up()
       { 
             Schema::create('contactus', function (Blueprint $table) {
                                 $table->increments('id');
                                 $table->string('name');
                                 $table->string('email');
                                 $table->string('subject');
                                 $table->text('message');
                                 $table->timestamps();
         });
     }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
           Schema::drop("contactus");
    }
}
And Run migration command,

php artisan migrate

4. Creating our Model

Run below command to generate our ContactUS Model file.
php artisan make:model ContactUS
Above command will create a file named ContactUS.php in our app directory, open this file add following code in it.


<?php namespace App; use Illuminate\Database\Eloquent\Model; class ContactUS extends Model { public $fillable = ['name','email','subject','message']; public $table = 'contactus'; } ?>

4. Creating Routes for contact us page

Open your routes/web.php file and add the following code to the route:

Route::get('contact-us', 'ContactUSController@contactUS');
Route::post('contact-us' ['as'=>'contactus.store','uses'=>'ContactUSController@contactSaveData']);

5. Creating Controller in Laravel

Run below command to generate our ContactUS Model file.

php artisan make:controller ContactUsController
Above command will create a file named ContactUsController.php in app/Http/Controllers/ directory, open this file add following code in it.

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\ContactUS; class ContactUSController extends Controller { /** * * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function contactUS() { return view('contact-us'); } /** * * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function contactSaveData(Request $request) { $this->validate($request, [ 'name' => 'required', 'email' => 'required|email', 'subject'=>'required', 'message' => 'required' ]); ContactUS::create($request->all()); return back()->with('success', 'Thanks for contacting us!'); } }

6. Creating View file for Contact us form.

In Laravel view files are kept in resources/views/ directory. Enter into resources/views/ directory for your Laravel application and create a new file named contact-us.blade.php and add following code in it.


<section class="contact-us">
    <div class="inner">
        <header>
            <h2>Get in Touch</h2>
        </header>
        @if (session('success'))
            <div class="alert alert-success" role="alert">
                {{ session('success') }}
            </div>
        @endif
        <form method="post" action="{{ route('contactus.store') }}">
            @csrf
            <div class="field half first form-group {{ $errors->has('name') ? ' has-error' : '' }}">
                <label for="name">Name <i>*</i></label>
                <input class="form-control" type="text" name="name" id="name" 
                        placeholder="Enter your name"/>
                @if ($errors->has('name'))
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $errors->first('name') }}</strong>
                    </span>
                @endif
            </div>

            <div class="field half first form-group {{ $errors->has('subject') ? ' has-error' : '' }}">
                <label for="subject">Subject <i>*</i></label>
                <input class="form-control" type="text" name="subject" id="subject" 
                    placeholder="Enter your subject name"/>
                @if ($errors->has('subject'))
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $errors->first('subject') }}</strong>
                    </span>
                @endif
            </div>

            <div class="field form-group {{ $errors->has('message') ? ' has-error' : '' }}">
                <label for="message">Message <i>*</i></label>
                <textarea class="form-control" name="message" id="message" rows="6" 
                       placeholder="Enter your message or query"></textarea>
                @if ($errors->has('message'))
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $errors->first('message') }}</strong>
                    </span>
                @endif
            </div>
            <ul class="actions">
                <li><input type="submit" value="Send Message" class="alt" /></li>
            </ul>
        </form>
    </div>
</section>


7. Creating Email template in Laravel.

Create a new directory name emails in resources/views/ and create a file named contactus.blade.php and add following code in it.

  
<h2>Hello Admin,</h2>
<p>You received an email from : {{ $name }}</p>
<p>Here are the details:</p>
<p>Name: {{ $name }}</p>
<p>Email: {{ $email }}</p>
<p>Subject: {{ $subject }}</p>
<p>Message: {{ $user_message }}</p>
<p>Thank You</p>


8. Configuring an Email server.

In this step, we are going to configure the Gmail SMTP server in Laravel.

Getting Gmail app password for sending an email in Laravel


  1. Login to your Gmail account from which you want to send emails.
  2. Click on https://myaccount.google.com/?utm_source=OGB&utm_medium=app&pli=1 link
  3. Click on Sign-in & security link
  4. Enable two-step verification for Gmail account
  5. Next, Click App Passwords link to generate a password for your mail app
Next, open your .env file and update the following information



MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com 
MAIL_PORT=587 
MAIL_USERNAME= your email address 
MAIL_PASSWORD= your gamil app password 
MAIL_ENCRYPTION=tls

 9. Sending Email to Admin

Generate your email class by running below command on terminal

php artisan make:mail contactus
Running above command will generate a new email class file name contactus.php under app/Mails directory.

Reopen Http/Controllers/ContactUSController.php and update following code in it.


<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\ContactUS;
class ContactUSController extends Controller
{
   /**
    * Show the application dashboard
    * @return \Illuminate\Http\Response
    */
   public function contactUS()
   {
       return view('contact-us');
   }
   /**
    * Show the application dashboard.
    *
    * @return \Illuminate\Http\Response
    */
   public function contactSaveData(Request $request)
   {
       $this->validate($request, [
        'name' => 'required',
          'subject' => 'required',
        'email' => 'required|email',
        'message' => 'required'
        ]);
      ContactUS::create($request->all());
    \Mail::send('emails.contactus',
       array(
           'name' => $request->get('name'),
           'email' => $request->get('email'),
          'subject' => $request->get('subject'),
           'user_message' => $request->get('message')
       ), function($message) use ($request)
   {
      $message->from('ABC@gmail.com');
      $message->to('XYZ@gmail.com', 'Admin')
                                       ->subject($request->get('subject'));
   });
    return back()->with('success', 'Thanks for contacting us!'); 
   }
}
Now your contact form is ready for demo.

10. Conclusion

After reading this tutorial you will able to create a contact us page for your website that will save users info in data and send and send user information on admin. Please let me know if you face any problem in creating contact us form using in this article in the comment section.

Post a Comment

0 Comments