Create a Contact Form in Laravel

devquora
devquora

Posted On: Feb 06, 2023

Create a Contact 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 visitor's details in your MySQL database as well also send an email to the website admin.

Laravel 5 Contact us form example from starch

Create a Contact Form in Laravel 5.7 Tutorial

1. Installing Laravel 5.7

Open your command prompt or your terminal and run the below commands to install and configure Laravel Framework

cd to your server directory and run the 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");
}
}
php artisan migrate 

Creating our Model

Run the below command to generate our ContactUS Model file.

   php artisan make:model ContactUS

The above command will create a file named ContactUS.php in our app directory, open this file and add the following code in it.

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

?

4. Creating Routes for the 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 the below command to generate our ContactUS Model file.

php artisan make:controller ContactUsController

The above command will create a file named ContactUsController.php in the app/Http/Controllers/ directory, open this file add the 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 the 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 the following code in it.

<!DOCTYPE html>
<html>
<head>
<title>Laravel 5.7 Contact us form example from starch</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
 

<!------ Include the above in your HEAD tag ---------->

<div class="container contact-form" style="margin-top:100px">
                    @if (session('status'))
                        <div class="alert alert-success">
                            {{ session('status') }}
                        </div>
                    @endif
                    @if (session('warning'))
                        <div class="alert alert-warning">
                            {{ session('warning') }}
                        </div>
                    @endif
            
            <form method="post" action="{{ route('contactus.store') }}">
			    {{ csrf_field() }}
                <h3>Contact Us</h3>
               <div class="row">
                    <div class="col-md-6">
                        <div class="form-group {{ $errors->has('name') ? ' has-error' : '' }}">
                            <input type="text" name="name" class="form-control" placeholder="Your Name *"  required />
				 @if ($errors->has('name'))
										<span class="help-block">
											<strong>{{ $errors->first('name') }}</strong>
										</span>
				 @endif
                        </div>
                        <div class="form-group {{ $errors->has('email') ? ' has-error' : '' }}">
                            <input type="email" name="email" class="form-control" placeholder="Your Email *"  required />
							 @if ($errors->has('email'))
										<span class="help-block">
											<strong>{{ $errors->first('email') }}</strong>
										</span>
							 @endif
                        </div>
                        <div class="form-group {{ $errors->has('subject') ? ' has-error' : '' }}">
                            <input type="text" name="subject" class="form-control" placeholder="Subject *"  />
							@if ($errors->has('subject'))
										<span class="help-block">
											<strong>{{ $errors->first('subject') }}</strong>
										</span>
							 @endif
                        </div>
                        <div class="form-group">
                            <input type="submit" name="btnSubmit" class="btn btn-primary btn-round btn-sm" value="Send Message" />
							
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group {{ $errors->has('message') ? ' has-error' : '' }}">
                            <textarea name="message" class="form-control" placeholder="Your Message *" style="width: 100%; height: 150px;" required></textarea>
			     @if ($errors->has('message'))
				<span class="help-block">
				<strong>{{ $errors->first('message') }}</strong>
				</span>
			    @endif
                        </div>
                    </div>
                </div>
            </form>
</div>
 
</body>
</html>

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 the 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 the below command on terminal

php artisan make:mail contactus

Running the above command will generate a new email class file name contactus.php under app/Mails directory

Reopen Http/Controllers/ContactUSController.php and update the 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('onlineinterviewquestions@gmail.com');
      $message->to('sharadjaiswal1411@gmail.com', 'Admin')->subject($request->get('subject'));
   });
 
    return back()->with('success', 'Thanks for contacting us!'); 
   }
}

Now your contact form is ready for demo. Please visit yourwebsite.com/contact-us to test and review the form

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 to admin. Please let me know if you face any problems in creating a contact us form using this article in the comment section.

Thank you :)

    Please Login or Register to leave a response.

    Related Articles

    Laravel Tutorials

    Laravel 5.5 Middleware Complete Tutorial

    In Laravel, you can think middleware as a system or tool that are used to filter all HTTP requests entering your application. Middleware works between request and response of our application. It sits ..

    Laravel Tutorials

    Laravel Pagination Ajax

    Creating Ajax based pagination is Laravel 5.6. Ajax (Asynchronous JavaScript and XML) is a technique to update a specific part of webpage asynchronously without reloading the page. In this article, we..

    Laravel Tutorials

    Laravel Pagination

    According to Wikipedia Pagination is a process of separating or dividing a document or digital contents into discrete pages. In Core PHP and other frameworks, paginating record is a painful task. Lara..