Laravel 9 Contact Form Example Tutorial
contact form in laravel 7 or 8
Here I will explain to you how to create a Contact Form in Laravel 7|8 and store the contact form data in MySQL database then you are at the right place.
Create a contact form in laravel 9
Contact Us form is a widely used feature required by almost every web or mobile application. In this Laravel contact form example tutorial, we will learn to create a contact form in Laravel using the Bootstrap 4 CSS Framework, validate contact form using Laravel built-in validation, send email to admin using Mailtrap.
Install Laravel Project
Install a new Laravel project using given below command.
composer create-project laravel/laravel --prefer-dist laravel-contact-form
Mode inside the project folder.
cd laravel-contact-form
Make Database Connection
Include your database configuration details in .env file to make the set up the connection between Laravel and MySQL.
DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=laravel_db DB_USERNAME=root DB_PASSWORD=
PL/SQL
Create Model and Run Database Migrations
Let us create the Model for contact form, in here we define the table Schema, execute the following command. It will create a Model and migration file. We have to create the table structure by specifying the values in the migrations file and also declare those values in the Model file as a Schema.
php artisan make:model Contact -m
Bash
Open database/migrations/timestamp_create_contacts_table.php file and add the values for contact us form that we stored in the MySQL database.
<?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'); } }
PHP
Add the following code in the app/Models/Contact.php file.
<?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']; }
PHP
Next, run the migration using the below command. Once the command is completed, go to the database and check the contacts table created with a name, email, phone, subject, and message values.
php artisan migrate
Bash
Create Contact Form Controller
Execute the following command to generate the contact form controller file.
php artisan make:controller ContactUsFormController
Bash
Open app/Http/Controller/ContactUsFormController.php file and add the following code in it.
<?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.'); } }
PHP
Import the Contact Model from the App folder.
Create two functions one for rendering contact form in view and to connect controller to form. The ContactUsForm() function is useful for storing user data in the database.
We need to define a ContactUsForm()
function and pass the $request
parameter to it. To validate the contact us form in Laravel, we will use the request object. This can allow us to use Laravelโs built-in validation.
Configure Contact Form Routes in Laravel
Go to routes/web.php file and define the two routes.
The first route is created with the GET method, and it renders the contact form in the view.
The Second route handles the various tasks such as form validation, storing form data in the database and displaying success message to the user on frontend.
<?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');
PHP
Add Custom CSS in Laravel
In this step, we will learn to add custom CSS in Laravel project. First, create /css/style.css file in public folder. Also, place the given CSS code in the newly created CSS file.
.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; }
CSS
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.
<link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">
Markup
Create Laravel 7|8 Contact Form with Bootstrap
Go to resources/views/ folder and create contact.blade.php file inside of it. Then, add the following code in it.
We created a beautiful contact form using Bootstrap CSS Framework. The @csrf
tag protects contact form from CROSS Site Request Forgery.
<!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>
Markup
Laravel Contact Form Validation
We are validating a contact form and accessing the errors for each form input field using $errors->has() method.
<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>
PHP
Set Up Laravel Email Template
Create resources/views/mail.blade.php file and add the given below code in it. We will add the contact form values which is sent by site visitor in this template, and you will see these values in your mailbox.
<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
PHP
Configure Laravel Email Server with Mailtrap
There are tons of other methods to set up mail a server in Laravel, but we are going to configure Email server in Laravel using Mailtrap.
Go to your Mailtrap SMTP settings tab, select Laravel from integration drop-down, Laravel provides a clean, simple API over the popular SwiftMailer library. With the default Laravel setup you can configure your mailing configuration by setting these values in the .env file in the root directory of your project.
MAIL_MAILER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=your_mailtrap_username MAIL_PASSWORD=your_mailtrap_password MAIL_ENCRYPTION=tls
PHP
Sending Email in Laravel
Execute the below command to setup the Laravelโs basic email function. Following command will create a new Mailable class with contact.php file inside the app/Mails/ directory.
php artisan make:mail contact
Bash
Again, go to Http/Controllers/ContactUsFormController.php file and replace the entire code with the given below code.
<?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('appfinz@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.'); } }
PHP
Your contact form is up and running. You can store the user data in the MySQL database and send email to the provided email address.
Start the application using the following command.
php artisan serve
Bash
Click on the URL to test the Contact Form application in Laravel:
Conclusion– With the help of this blog you can successfully create a contact form in laravel 7
We hope by the end of this blog you have successfully created your own Contact Us page. For further information, you may contact Appfinz Technologies – a web development company, as we are a highly experienced Laravel Development Company. We do provide professional Laravel Development services to our clients so that they get maximum benefit from their project.
If you want to hire Laravel Developers you may contact our business development executives at info@appfinz.com who will assist you accordingly.