Monday 13 April 2020

Laravel Contact Form with Send Email & jQuery Validation



In this post we will make Contact Form in Laravel with jQuery Form validation and that contact form will sends you an email. That means in this post we will learn two topic in Laravel framework. One topic is to validate Laravel Form data by using jQuery form validation plugin and second topic is that how to send email from contact form using Laravel. So, in this post we will learn how to Send Email From Contact Form in Laravel with jQuery Form Validation. Here first will make contact form in Laravel and then after by using jQuery form validation plugin we will validate form data and then after we will send form data to server which will send email to us and insert data into Mysql database.

We all know Laravel framework is most popular PHP framework which has been provide us multiple solution for our web development problem. In web development contact us form is required web page for any website. So in every website we need to add contact in website. So in Laravel framework we will make contact page for our website. Contact page main functionality is that user has write their query in contact form and when submit that form then customer query will be received to us via email. So, here we will make contact form which will send us email. So, in Laravel framework will make contact us form with sending email functionality.

But before sending of email, first we want to validate contact us form data. For this validate contact form data here we have use jQuery Form Validation plugin. By using this jQuery Form validation plugin, we will validate Laravel contact us form data before submitting of form data. This plugin has validate form data at client side before submitting of form data. This plugin has many rules like required, minlength, maxlenth, email etc for validate most of all form input fields.

For create Contact page in Laravel with jQuery Validation and Email sending feature, we have to follow following step.

  1. Install Laravel framework
  2. Configure Database connection
  3. Create Table in Mysql Database using Migration
  4. Create Model
  5. Create Controller
  6. Create View
  7. Set Route


Install Laravel framework


For use Laravel framework for web development, first we have to download Laravel framework and install in our local computer. For this first we have to go command prompt and run composer command. After this we have to go our working directory in which we want to download install and run following command in command prompt.


composer create-project --prefer-dist laravel/laravel laravel7


This command will make laravel7 folder in define directory and in that it will download and install Laravel framework.

Configure Database connection


Next we have to make database connection in this Laravel application. For this we have to open .env file and in this file we have to define Mysql database configuration, which you can see below.


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





Create Table in Mysql Database using Migration


After making database configuration, now we are ready for make contact us form in Laravel with form data validate by jQuery plugin and send email. First we want to create table in mysql database from this Laravel application by using migration. For this we have to go command prompt and write following command.


php artisan make:model Contactus -m


This command will make migration file in database/migrations folder and and it will also make model class in app folder also. First we have to open database/migrations folder file and under that file define table column which you want to add in table.


<?php

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

class CreateContactusesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contactuses', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->text('message');
            $table->timestamps();
        });
    }

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


After this we have again go to command prompt and write following command. This command will make contactuses table in your define mysql database.


php artisan migrate


Create Model


Here we have use model for database operation and model file has been already made while we have run php artisan make:model Contactus -m command and model class file has been make in app folder. We have to open that file and define mysql table column in that file.

app/Contactus.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Contactus extends Model
{
    protected $fillable = ['name', 'email', 'message'];
}

?>


Create Controller


In Laravel framework Controller class has been used for handle http request. In Laravel framework for create controller class via composer command, first we have to go command prompt and write following command.


php artisan make:controller ContactusController


This command will make ContactusController.php file in app/Http/Controllers foldeer. In this controller class, First we have write use Redirect; statement for redirect url from one url to another url. Sameway for send email from laravel application, we have write use Mail; statement. For include model class under this file, we have write use App\Contactus; statement. For create Contact form with jQuery Validation and sending email functionality, we have make following method.
index() - This is root method of this class, and it has been load contact_us.blade.php file in browser.
submit(Request $request) - This method has been received request for submit contact form data after jquery form data validation. In this method first it has been send email from laravel application. For email sending in laravel, first we want to configure email credential in .env file. .env

MAIL_DRIVER=smtp
MAIL_HOST=xxx
MAIL_PORT=xxx
MAIL_USERNAME=xxxx
MAIL_PASSWORD=xxxx
MAIL_ENCRYPTION=tls


After this method has store contact form data in Mysql table and then after redirect page to index() method with success message.

app/Http/Controllers/ContactusController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Redirect;
use Response;
use Mail;
use App\Contactus;

class ContactusController extends Controller
{
    function index()
    {
     return view('contact_us');
    }

    function submit(Request $request)
    {
     $data = array(
      'name_data'  => $request->name,
      'email_data' => $request->email,
      'message_data' => $request->message
     );

     Mail::send('mail', $data, function($message) use ($request){
      $message->to('web-tutorial@programmer.net', 'Webslesson')->subject('New Enquiry received ' . $request->name);
      $message->from($request->email, $request->name);
     });

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

     return redirect()->back()->with('success', 'Message has been sent...');
    }
}
?>


Create View


In Laravel framework, View file has been display html output in browser. View file has been store in resources/views folder. Here we have create two file, one is contact_us.blade.php and second is mail.blade.php file.

In contact_us.php file, we have make contact us form and that form data has been validate by using jQuery Validation plugin. Below you can find the how we have validate contact form data by using jQuery Form validation plugin.

resources/views/contact_us.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery Form Validation in Laravel with Send Email</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
    <style>
    .error
    {
     color:#FF0000;
    }
    </style>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">jQuery Form Validation in Laravel with Send Email</h3>
     <br />
     @if($message = Session::get('success'))

          <div class="alert alert-success alert-block">
            <button type="button" class="close" data-dismiss="alert">×</button>
            <strong>{{ $message }}</strong>
          </div>
          @endif
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">Contact Us</h3>
      </div>
      
      <div class="panel-body">
       <form id="contact_form" method="post" action="{{ url('contact_us/submit') }}">
              @csrf
              <div class="form-group">
                <label for="name">Name</label>
                <input type="text" name="name" class="form-control" id="name" placeholder="Enter Name Detail">
              </div>
              <div class="form-group">
                <label for="email">Email Address</label>
                <input type="text" name="email" class="form-control" id="email" placeholder="Enter Email Detail">
              </div>
              <div class="form-group">
                <label for="message">Message</label>
                <textarea name="message" class="form-control" id="message" placeholder="Enter Message Detail"></textarea>
              </div>
              <div class="form-group">
                <input type="submit" class="btn btn-primary" value="Send" />
              </div>
            </form>
      </div>
     </div>
        </div>
 </body>
</html>


<script>
$(document).ready(function(){

 if($("#contact_form").length > 0)
  {
    $('#contact_form').validate({
      rules:{
        name : {
          required : true,
          maxlength : 50
        },
        email : {
          required : true,
          maxlength : 50, 
          email : true
        },
        message : {
          required : true,
          minlength : 50,
          maxlength : 500
        }
      },
      messages : {
        name : {
          required : 'Enter Name Detail',
          maxlength : 'Name should not be more than 50 character'
        },
        email : {
          required : 'Enter Email Detail',
          email : 'Enter Valid Email Detail',
          maxlength : 'Email should not be more than 50 character'
        },
        message : {
          required : 'Enter Message Detail',
          minlength : 'Message Details must be minimum 50 character long',
          maxlength : 'Message Details must be maximum 500 character long'
        }
      }
    });
  }

});
</script>




And second mail.blade.php file has been used as Email body content. In this file {{ $name_data }} and {{ $message_data }} variable value has been get from ContactusController.php controller class submit() method.

resources/views/mail.blade.php

<p>This is new enquiry from {{ $name_data }}</p>
<p>Following is the query.</p>
<p>{{ $message_data }} </p>


Set Route


In Laravel framework, we have to set the route of Controller class all method. For set route, we have to open routes/web.php file and define following route.


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

Route::get('contact_us', 'ContactusController@index');

Route::post('contact_us/submit', 'ContactusController@submit');


So, here our code is ready, now we have want to test ouptut in browser. So, first we need to start laravel server, so first we have go to command prompt and run following command.


php artisan serve


This command will start Laravel server and it will provide us base url of our Laravel application. For test above code, we have to write following url in browser.


http://127.0.0.1:8000/contact_us


So, this is complete step by step process for how to make contact form in Laravel framework and then after how to validate contact form data by using jQuery Validation plugin and how to send email from Laravel application. If you have any query regarding this tutorial, you can also check our video tutorial at the start of this tutorial.

4 comments:

  1. I request can you please create a video & Source code on realtime chat appilcation in laravel with the help of Vue js and Pusher and latest laravel application.

    thanks in advanced!!

    ReplyDelete
  2. please how i send customer order name item and prise and totile price to my my email please how i do that

    ReplyDelete