Laravel 9 Contact Us Form with Send Mail Example Tutorial

Laravel 9 Contact Us Form with Send Email example; In this tutorial you will learn how to create contact us form with email send and store to mysql database in Laravel app.

We will use form validation, storing data in database, email sending and success message in this example. This example show you best ideas to add contact us form in laravel 9 app and email sending example.

Create Contact Form in Laravel 9 App

Use to follow the following steps to create contact us form in laravel with send mail example:

  • Step 1: Install Laravel App
  • Step 2: Connect App to Database
  • Step 3: Create Model and migration File
  • Step 4: Add Routes
  • Step 5: Create Controller
  • Step 6: Create Blade File
  • Step 7: Create Email Blade File
  • Step 8: Configuring an Email server
  • Step 9: Sending Email in laravel
  • Step 10: Update Controller Using Mail Function
  • Step 11: Start Development Server

Install Laravel App

In the beginning, open a terminal window and use the suggested command to create a fresh laravel application:

composer create-project --prefer-dist laravel/laravel laravel-contact-us-example

Go inside the app:

cd laravel-contact-us-example

Configuring Database

Next, insert database details in .env config file, it makes the laravel connection with the database:

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

Create Model and Migration File

In this step, create a migration for contacts table and Contact Model in laravel app. So run the following command on command prompt:

php artisan make:model Contact -m

Next, navigate the App/Models directory and open Contact.php model file then add the following code in it;

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use HasFactory;

    protected $fillable = [
      'name', 'email', 'mobile_number', 'subject', 'message'
    ];
}

Next, Navigate to database/migrations and open create_contacts_table.php then put the following code on it;

database/migrations/2020_09_02_161223_create_contacts_table.php

<?php 
 
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
 
class CreateContactsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/ 
public function up()
{
	
	Schema::create('contacts', function (Blueprint $table) { 
	$table->id();
	$table->string('name'); 
	$table->string('email'); 
        $table->string('phone_number')->nullable(); 
	$table->string('subject')->nullable();
	$table->text('message'); 
	$table->timestamps(); 
	});

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

Now run the migration command for generating new contacts table in database:

php artisan migrate

Now you can check in your database a new table contacts is created.

Make Routes

Now you need to create routes go in routes/web.php. Then add the following routes into web.php file, as follow:

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\ContactController;

Route::get('contact-us', [ ContactController::class, 'getContact' ]);
Route::post('contact-us', [ ContactController::class, 'saveContact' ])->name('contact-us');

Create Controller 

In this step, execute the following command to create one controller file name ContactController.php:

php artisan make:controller ContactController

After running this command you will find new file in this path “app/Http/Controllers/ContactController.php”. Open the file and put the below code on it:

<?php 
namespace App\Http\Controllers;

use Illuminate\Http\Request; 
use App\Contact; 
use Mail; 

class ContactController extends Controller { 

      public function getContact() { 

       return view('contact-us'); 
     } 

      public function saveContact(Request $request) { 

        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email',
            'subject' => 'required',
            'phone_number' => 'required',
            'message' => 'required'
        ]);

        $contact = new Contact;

        $contact->name = $request->name;
        $contact->email = $request->email;
        $contact->subject = $request->subject;
        $contact->phone_number = $request->phone_number;
        $contact->message = $request->message;

        $contact->save();
        
        return back()->with('success', 'Thank you for contact us!');

    }
}

Create Blade File

In this step, go to resources/views folder and create blade view file named as contact-us.blade.php.

Now open the resources/views/contact-us.blade.php file and put the folowong code on it;

@extends('dashboard')
@section('content')

<div class="content">
   <div class="row">
     <div class="col-md-12">
       <div class="card card-user">
         <div class="card-header">
           <h5 class="card-title">Contact Us</h5>
         </div>
        <div class="card-body">
           @if(Session::has('success'))
              <div class="alert alert-success">
        	    {{ Session::get('success') }}
               </div>
           @endif
           
          <form method="post" action="{{ route('contact-us') }}">
             {{csrf_field()}}
             <div class="row">
               <div class="col-md-12">
                 <div class="form-group">
                   <label> Name </label>
                   <input type="text" class="form-control @error('name') is-invalid @enderror" placeholder="Name" name="name">
                   @error('name')
                       <span class="invalid-feedback" role="alert">
                           <strong>{{ $message }}</strong>
                       </span>
                   @enderror
                 </div>
               </div>
             <div class="col-md-12">
               <div class="form-group">
                   <label> Email </label>
                   <input type="text" class="form-control @error('email') is-invalid @enderror" placeholder="Email" name="email">
                   @error('email')
                       <span class="invalid-feedback" role="alert">
                           <strong>{{ $message }}</strong>
                       </span>
                   @enderror
                 </div>
               </div>   
             <div class="col-md-12">
                <div class="form-group">
                   <label> Phone Number </label>
                   <input type="text" class="form-control @error('phone_number') is-invalid @enderror" placeholder="Phone Number" name="phone_number">
                   @error('phone_number')
                       <span class="invalid-feedback" role="alert">
                           <strong>{{ $message }}</strong>
                       </span>
                   @enderror
                 </div>
               </div>
              <div class="col-md-12">
                 <div class="form-group">
                   <label> Subject </label>
                   <input type="text" class="form-control @error('subject') is-invalid @enderror" placeholder="Subject" name="subject">
                   @error('subject')
                       <span class="invalid-feedback" role="alert">
                           <strong>{{ $message }}</strong>
                       </span>
                   @enderror
                 </div>
               </div>
              <div class="col-md-12">
                <div class="form-group">
                   <label> Message </label>
                   <textarea class="form-control textarea @error('message') is-invalid @enderror" placeholder="Message" name="message"></textarea>
                   @error('message')
                       <span class="invalid-feedback" role="alert">
                           <strong>{{ $message }}</strong>
                       </span>
                   @enderror
                 </div>
               </div>
             </div>
             <div class="row">
              <div class="update ml-auto mr-auto">
                 <button type="submit" class="btn btn-primary btn-round">Send</button>
               </div>
             </div>
           </form>
         </div>
       </div>
     </div>
   </div>
</div>

@endsection

Create Email Blade File

Next, same navigate the resources/views directory and create an another blade file contact-email.blade.php. This file content show in you mail inbox.

Now open resources/views/contact-email.blade.php blade file and put the same content as below;

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

Configuring an Email server

In this step, we are going to configure the MailTrap SMTP server in Laravel. Firstly you need to crate an account in mailtrap.io.

Login your mailtrap account and go SMTP setting copy username and password details and add in your .env file just seeding below.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=587
MAIL_USERNAME=331e7######### Your mailtrap username
MAIL_PASSWORD=25a10#########Your mailtrap password
MAIL_ENCRYPTION=tls

Sending Email in Laravel

So after cofiguration all your laravel contact page, you need to add below code in your ContactController after save button. In bellow we have added the mail function where your could easily send the user details to mailtrap.

\Mail::send('contact_email',
             array(
                 'name' => $request->get('name'),
                 'email' => $request->get('email'),
                 'subject' => $request->get('subject'),
                 'phone_number' => $request->get('phone_number'),
                 'user_message' => $request->get('message'),
             ), function($message) use ($request)
               {
                  $message->from($request->email);
                  $message->to('admin@gmail.com');
               });

Update Controller Using Mail Function

If you have not idea to how to add mail function in your controller, don’t worry we added the here below check how to add the mail function after data storing. This is updated controller to sending mail after creating contact form in laravel.

<?php 

namespace App\Http\Controllers; 
use Illuminate\Http\Request; 
use App\Contact; use Mail; 

class ContactController extends Controller { 

      public function getContact() { 

       return view('contact_us'); 
      } 

     public function saveContact(Request $request) { 
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email',
            'subject' => 'required',
            'phone_number' => 'required',
            'message' => 'required'
        ]);

        $contact = new Contact;

        $contact->name = $request->name;
        $contact->email = $request->email;
        $contact->subject = $request->subject;
        $contact->phone_number = $request->phone_number;
        $contact->message = $request->message;

        $contact->save();

        \Mail::send('contact_email',
             array(
                 'name' => $request->get('name'),
                 'email' => $request->get('email'),
                 'subject' => $request->get('subject'),
                 'phone_number' => $request->get('phone_number'),
                 'user_message' => $request->get('message'),
             ), function($message) use ($request)
               {
                  $message->from($request->email);
                  $message->to('admin@example.com');
               });

          return back()->with('success', 'Thank you for contact us!');

    }
}

Start Devlopment Server

Start the application using the following command.

php artisan serve

Click on the URL to test the Contact Form application in Laravel:

http://127.0.0.1:8000/contact

So, finally the laravel contact us form example tutorial we have understood how to create a Contact Form in Laravel, set up an email server with Mailtrap.io, and send an email to Admin from Laravel application.

1 thought on “Laravel 9 Contact Us Form with Send Mail Example Tutorial”

Leave a Comment