In this tutorial you will learn about the How to Create Contact Form In Laravel 8 Example Tutorial and its application with practical example.
In this How to Create Contact Form In Laravel 8 Example Tutorial I’ll show you how to create simple contact form with validation in laravel 8. In this tutorial you will learn to create contact form with validation and send mail in laravel 8. In this article I will also show you how to submit and validate contact form data before submit in laravel. We will also send an email when contact form is submitted then save contact form input in the database. In this example I will guide you through creating contact form in laravel, validating contact form, submitting contact form and then sending email when contact form is submitted.
- How to Create Contact Form In Laravel 8 Example Tutorial
- Make Database Connection
- Create Model and Run Database Migrations
- Create Contact Form Controller
- Configure Contact Form Routes in Laravel
- Add Custom CSS in Laravel
- Create Laravel 8 Contact Form with Bootstrap
- Laravel Contact Form Validation
- Set Up Laravel Email Template
- Configure Laravel Email Server with Mailtrap
- Sending Email in Laravel
How to Create Contact Form In Laravel 8 Example Tutorial
In this step by step tutorial I will demonstrate you how to create simple contact form with validation and send email in laravel. Please follow the instruction given below:
- Install Laravel Project
- Make Database Connection
- Model and Migrations
- Create Controller
- Configure Contact Form Routes
- Add Custom CSS in Laravel
- Create Laravel Contact Form with Bootstrap
- Laravel Contact Form Validation
- Set Up Email Template
- Set Up Laravel Email Server
- Send Email in Laravel
Install Laravel Project
First of all we need to create a fresh laravel project, download and install Laravel 8 using the below command
1 |
composer create-project laravel/laravel --prefer-dist laravel-contact-form |
switch into the project directory:
1 |
cd laravel-contact-form |
Make Database Connection
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=laravel_db DB_USERNAME=root DB_PASSWORD= |
Create Model and Run Database Migrations
Now, in this step we will create model and migration file. Please run the following command:
1 |
php artisan make:model Contact -m |
Open database/migrations/timestamp_create_contacts_table.php file and add the values for contact us form that we stored in the MySQL database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; 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'); $table->string('subject'); $table->text('message'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('contacts'); } } |
Next, open app/Models/Contact.php file and add the $fillable property in the model as following.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Contact extends Model { use HasFactory; public $fillable = ['name', 'email', 'phone', 'subject', 'message']; } |
Now, run the migration to create database table using following artisan command:
1 |
php artisan migrate |
Create Contact Form Controller
Now, lets create a controller named ContactUsFormController using command given below –
1 |
php artisan make:controller ContactUsFormController |
Open app/Http/Controller/ContactUsFormController.php file and add the following code in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Contact; class ContactUsFormController extends Controller { // Create Contact Form public function createForm(Request $request) { return view('contact'); } // Store Contact Form data public function ContactUsForm(Request $request) { // Form validation $this->validate($request, [ 'name' => 'required', 'email' => 'required|email', 'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10', 'subject'=>'required', 'message' => 'required' ]); // Store data in database Contact::create($request->all()); // return back()->with('success', 'We have received your message and would like to thank you for writing to us.'); } } |
Configure Contact Form Routes in Laravel
After this, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\ContactUsFormController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/contact', [ContactUsFormController::class, 'createForm']); Route::post('/contact', [ContactUsFormController::class, 'ContactUsForm'])->name('contact.store'); |
Add Custom CSS in Laravel
Lets create /css/style.css file in public folder and put the below CSS code in the newly created CSS file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
.container { max-width: 500px; margin: 50px auto; text-align: left; font-family: sans-serif; } form { border: 1px solid #1A33FF; background: #ecf5fc; padding: 40px 50px 45px; } .form-control:focus { border-color: #000; box-shadow: none; } label { font-weight: 600; } .error { color: red; font-weight: 400; display: block; padding: 6px 0; font-size: 14px; } .form-control.error { border-color: red; padding: .375rem .75rem; } |
Now, you can easily call this CSS file in the Laravel blade template, we need to paste the following code in the view/contact.blade.php file to add the custom CSS in Laravel.
1 |
<link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}"> |
Create Laravel 8 Contact Form with Bootstrap
Go to resources/views/ folder and create contact.blade.php blade view file inside of it. Then, put the following code in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}"> </head> <body> <div class="container mt-5"> <!-- Success message --> @if(Session::has('success')) <div class="alert alert-success"> {{Session::get('success')}} </div> @endif <form action="" method="post" action="{{ route('contact.store') }}"> <!-- CROSS Site Request Forgery Protection --> @csrf <div class="form-group"> <label>Name</label> <input type="text" class="form-control" name="name" id="name"> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" name="email" id="email"> </div> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control" name="phone" id="phone"> </div> <div class="form-group"> <label>Subject</label> <input type="text" class="form-control" name="subject" id="subject"> </div> <div class="form-group"> <label>Message</label> <textarea class="form-control" name="message" id="message" rows="4"></textarea> </div> <input type="submit" name="send" value="Submit" class="btn btn-dark btn-block"> </form> </div> </body> </html> |
Laravel Contact Form Validation
Now we will add validation on contact form input field using $errors->has() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
<form action="" method="post" action="{{ route('contact.store') }}"> @csrf <div class="form-group"> <label>Name</label> <input type="text" class="form-control {{ $errors->has('name') ? 'error' : '' }}" name="name" id="name"> <!-- Error --> @if ($errors->has('name')) <div class="error"> {{ $errors->first('name') }} </div> @endif </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control {{ $errors->has('email') ? 'error' : '' }}" name="email" id="email"> @if ($errors->has('email')) <div class="error"> {{ $errors->first('email') }} </div> @endif </div> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control {{ $errors->has('phone') ? 'error' : '' }}" name="phone" id="phone"> @if ($errors->has('phone')) <div class="error"> {{ $errors->first('phone') }} </div> @endif </div> <div class="form-group"> <label>Subject</label> <input type="text" class="form-control {{ $errors->has('subject') ? 'error' : '' }}" name="subject" id="subject"> @if ($errors->has('subject')) <div class="error"> {{ $errors->first('subject') }} </div> @endif </div> <div class="form-group"> <label>Message</label> <textarea class="form-control {{ $errors->has('message') ? 'error' : '' }}" name="message" id="message" rows="4"></textarea> @if ($errors->has('message')) <div class="error"> {{ $errors->first('message') }} </div> @endif </div> <input type="submit" name="send" value="Submit" class="btn btn-dark btn-block"> </form> |
Set Up Laravel Email Template
Create resources/views/mail.blade.php file and add the given below code in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<h2>Hello</h2> <br><br> You have got an email from : {{ $name }} <br><br> User details: <br><br> Name: {{ $name }} <br> Email: {{ $email }} <br> Phone: {{ $phone }} <br> Subject: {{ $subject }} <br> Message: {{ $user_query }} <br><br> Thanks |
Configure Laravel Email Server with Mailtrap
1 2 3 4 5 6 |
MAIL_MAILER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=your_mailtrap_username MAIL_PASSWORD=your_mailtrap_password MAIL_ENCRYPTION=tls |
Sending Email in Laravel
Now use the following command to create a new Mailable class with contact.php file inside the app/Mails/ directory.
1 |
php artisan make:mail contact |
Now, go to Http/Controllers/ContactUsFormController.php file and put the following code with the given below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Contact; use Mail; class ContactUsFormController extends Controller { // Create Contact Form public function createForm(Request $request) { return view('contact'); } // Store Contact Form data public function ContactUsForm(Request $request) { // Form validation $this->validate($request, [ 'name' => 'required', 'email' => 'required|email', 'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10', 'subject'=>'required', 'message' => 'required' ]); // Store data in database Contact::create($request->all()); // Send mail to admin \Mail::send('mail', array( 'name' => $request->get('name'), 'email' => $request->get('email'), 'phone' => $request->get('phone'), 'subject' => $request->get('subject'), 'user_query' => $request->get('message'), ), function($message) use ($request){ $message->from($request->email); $message->to('digambersingh126@gmail.com', 'Admin')->subject($request->get('subject')); }); return back()->with('success', 'We have received your message and would like to thank you for writing to us.'); } } |
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Now, open the following URL in browser to see the output –