DEV Community

Cover image for Laravel Contact Form With Email
Saquib Rizwan
Saquib Rizwan

Posted on • Edited on

Laravel Contact Form With Email

Laravel is a popular PHP framework for creating dynamic websites and web application. Laravel offers a wide range of functionalities that take care of routine project requirements such as routing, authentication, sessions and caching. A Contact Us form is another routine functionality present at all websites these days.

In this article, I am going to show you how to easily create a contact form in Laravel with email.

Install Laravel Application

For demonstrating the Laravel contact form, I will be creating and hosting Laravel application on Cloudways. Sign up at Cloudways for free and login to your account. Next:

  • Create a new server.
  • Fill in the server and the application details and select Laravel as the application.

That’s it, within a few clicks you have installed and setup a fully functional Laravel application.

Install Laravel

Install Laravel Collective HTML Package

To create the form in Laravel, install the laravelcollective/html package for Form facade. Go to the Cloudways platform and open the Server tab. Launch the SSH terminal and login to your server using the Master Credentials.

Launch SSH

Now go to the root of your application:

cd applications
cd applicationname/public_html
composer require laravelcollective/html
Enter fullscreen mode Exit fullscreen mode

Now that the package is installed, goto config/app.php file and add the service provider and alias:

config/app.php


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

Enter fullscreen mode Exit fullscreen mode

Database Configuration

The next step is to configure the database. Open the Application tab in the Cloudways platform and go to Application Access details. Use these database credentials.

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

Enter fullscreen mode Exit fullscreen mode

Create Migrations for Contact Us Table

Go to the public root folder of the 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
Enter fullscreen mode Exit fullscreen mode

That will create the migration.

After that, go to database/migration/date_ create_contact_us_table.php and add the following code to 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");
    }
}

Enter fullscreen mode Exit fullscreen mode

Now run the following command:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Create the Model

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

php artisan make:model ContactUS
Enter fullscreen mode Exit fullscreen mode

After successfully creating 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'];

}
Enter fullscreen mode Exit fullscreen mode

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']);
Enter fullscreen mode Exit fullscreen mode

Create the Controller

Now create a controller for handling the requests from the routes. Now go to app/Http/Controllers/ContactUSController.php and add the following code to 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!');
   }
}

Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

The contact form is now functional.

On submitting the form, the data will be stored in the database. The next step is of 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>

Enter fullscreen mode Exit fullscreen mode

Sending the Email

To understand the steps involved in this step, read 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>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!'); 
   }
}
Enter fullscreen mode Exit fullscreen mode

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).

Launch App

Check the DEMO to see the application in action.

The Final Words

In this tutorial, I showed you how to create a contact form in Laravel with the functionality of emailing the information to a prespecified email address.

Top comments (3)

Collapse
 
anmollohana profile image
anmollohana

A dynamic contact form is a great way to make your site interactive and collect user data. A good contact form doesn't just send an email; it also includes instructions on what to do next and a tracking ID.
A contact form on your website can be necessary for a small business. A contact form can help you build your database and send leads to your inbox. Thank you for sharing this way to build a contact form using Laravel.

Collapse
 
youknub profile image
Rahman G

I get the error message

InvalidArgumentException
View [email] not found.

Collapse
 
rizwan_saquib profile image
Saquib Rizwan • Edited

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>