Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Setup Laravel 5.7 Application in Just 1-click on Different Cloud Providers Like GCE , AWS , DO , Linode , Vultr Deploy Now!

Create a Contact Form in Laravel that Sends You an Email

Updated on June 22, 2017

5 Min Read
Reading Time: 5 minutes

Laravel is well known for providing multiple solutions for a problem. This is one of the main reasons of the popularity of the framework. Popular Laravel solutions cover routine functionality such as authentication, sessions, routing, and caching. laravel contact form Contact Us forms are another routine functionality that is a requirement of more or less every website. In this article, I am going to demonstrate how you can easily create a contact form in Laravel with email. To understand the functionality of Laravel mail function. I suggest you read my previous article on sending emails in Laravel.

Install Laravel

To quickly setup a Laravel application, sign up at Cloudways for free. Login to your account and create a new server. Fill in the server and the application detail and select Laravel as your application. That’s it, you have just installed a new application within a few clicks on the Cloudways platform.

Install Form Package

To create forms in Laravel, I will use laravelcollective/html package for Form facade. In order to do that, go to your Cloudways platform and open the server tab. Launch the SSH terminal and login to your server using the Master Credentials. Now go to the root of your application by typing following commands.

cd applications
cd applicationname/public_html

composer require laravelcollective/html

After successful installation of the package, goto config/app.php file and add service provider and alias:

config/app.php

'providers' => [
....
'Collective\Html\HtmlServiceProvider',
],
'aliases' => [
....
'Form' => 'Collective\Html\FormFacade',
],

Configure the Database

Now that you have installed the package, the next step is database configuration. Open the Application tab in the Cloudways platform. In the application access detail, you will be able to see the database credentials for your application. Now go to the .env file, located in the application public root folder and add the credentials there.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE= your.database.name                                                                                                                            
DB_USERNAME= your.database.username                                                                                                                             
DB_PASSWORD= your.database.password

Create Contact us Table Using Database Migrations

Go to the public root folder of your application and run the following command to create the database migration for creating the Contact Us model.

php artisan make:migration create_contact_us_table

Now that the migration has been created, go to database/migration/date_ create_contact_us_table.php and add the 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->text('message'); $table->timestamps(); });
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop("contactus");
}
}

Now run the following command

php artisan migrate

Now that the migration has been created, let’s create the Contact us model.

Create the Model

Go to your public root folder of your application and type the following command:

php artisan make:model ContactUS

Now that you have successfully created the ContactUS model, go to app/ContactUS.php and add the following code in the file:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ContactUS extends Model
{

public $table = 'contactus';

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

}

Next, I will create the route.

Create the Route

Go to routes/web.php and add the following code to the route:

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

Create the Controller

After setting the routes, I will create a controller to handle the requests from the routes. Now go to app/Http/Controllers/ContactUSController.php and 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('contactUS');
   }

   /**
    * Show the application dashboard.
    *
    * @return \Illuminate\Http\Response
    */
   public function contactUSPost(Request $request)
   {
       $this->validate($request, [
        'name' => 'required',
        'email' => 'required|email',
        'message' => 'required'
        ]);

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

       return back()->with('success', 'Thanks for contacting us!');
   }
}

Create the View

Everything is now ready and I will now create the layout of the form.  Go to resources/views/ and create a file contactUS.blade.php. Place the following code in it:

<!DOCTYPE html>
<html>
<head>
<title>Laravel 5.4 Cloudways Contact US Form Example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>

<div class="container">
<h1>Contact US Form</h1>

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

{!! Form::open(['route'=>'contactus.store']) !!}

<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
{!! Form::label('Name:') !!}
{!! Form::text('name', old('name'), ['class'=>'form-control', 'placeholder'=>'Enter Name']) !!}
<span class="text-danger">{{ $errors->first('name') }}</span>
</div>

<div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
{!! Form::label('Email:') !!}
{!! Form::text('email', old('email'), ['class'=>'form-control', 'placeholder'=>'Enter Email']) !!}
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>

<div class="form-group {{ $errors->has('message') ? 'has-error' : '' }}">
{!! Form::label('Message:') !!}
{!! Form::textarea('message', old('message'), ['class'=>'form-control', 'placeholder'=>'Enter Message']) !!}
<span class="text-danger">{{ $errors->first('message') }}</span>
</div>

<div class="form-group">
<button class="btn btn-success">Contact US!</button>
</div>

{!! Form::close() !!}

</div>

</body>
</html>

The contact form is now functional. On submitting the form, the data will be stored in the database. I will now make the form email the information.

Now create another view, email.blade.php and add the following code in it.

You received a message from : {{ $name }}

<p>
Name: {{ $name }}
</p>

<p>
Email: {{ $email }}
</p>

<p>
Message: {{ $user_message }}
</p>

Sending the Email

First read my previous article on sending email in Laravel.  Now that you have read the steps, it is time to implement the process. First, setup the basic Laravel mail function through PHP Artisan. Use the following command in the terminal:

php artisan make:mail <name of mailable>

After that, login to your Gmail account. Under My account > Sign In And Security > Sign In to Google, enable two-step verification, and then generate the app password. Next, add the app password in the  .env file with the following configurations.

MAIL_DRIVER=smtp

MAIL_HOST=smtp.gmail.com

MAIL_PORT=587

MAIL_USERNAME= your.email@gmail.com

MAIL_PASSWORD= your.generated.app.password

MAIL_ENCRYPTION=tls

Now that the configuration is done, update ContactUsController.php with the following code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\ContactUS;
use Mail;

class ContactUSController extends Controller
{
   public function contactUS()
{
return view('contactUS');
} 
   /** * Show the application dashboard. * * @return \Illuminate\Http\Response */
   public function contactUSPost(Request $request) 
   {
    $this->validate($request, [ 'name' => 'required', 'email' => 'required|email', 'message' => 'required' ]);
    ContactUS::create($request->all()); 
   
    Mail::send('email',
       array(
           'name' => $request->get('name'),
           'email' => $request->get('email'),
           'user_message' => $request->get('message')
       ), function($message)
   {
       $message->from('saquib.gt@gmail.com');
       $message->to('saquib.rizwan@cloudways.com', 'Admin')->subject('Cloudways Feedback');
   });

    return back()->with('success', 'Thanks for contacting us!'); 
   }
}

The contact form is now ready for deployment. It will save the data in the database and email it to the given email address as well. To test the Contact Us form, go to the application and click on launch application (remember to add /contact-us to the URL).   Check the demo to see the application in action.

You Might Also Like: Create Contact Form in HTML and PHP

The Final Words

In this tutorial, I have demonstrated how to create a contact form in Laravel with the functionality of emailing the information to a prespecified email address. Sign up at Cloudways for awesome Laravel hosting and tutorials.

Share your opinion in the comment section. COMMENT NOW

Saquib Rizwan

Saquib is a PHP Community Expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is well versed in PHP and regularly contributes to open source projects. For fun, he enjoys gaming, movies and hanging out with friends. You can email him at saquib.rizwan@cloudways.com

Launch Laravel apps with 1-Click Install. Painless Server Management

Deploy your apps on optimized Laravel hosting servers.

Get Our Newsletter
Be the first to get the latest updates and tutorials.

THERE’S MORE TO READ.