- This topic has 0 replies, 1 voice, and was last updated 1 year, 3 months ago by
Tochukwu.
- AuthorPosts
- December 16, 2019 at 4:06 pm #82253Spectator@tochukwu
A contact form is often used on websites to get user feedback. A slightly different version, called a subscription form, is used to collect the email addresses of your readers and then add them to your list of subscribers in your database.
This article will focus on contact forms and explain how they are created in Laravel. Everything will be discussed – including the actual process of sending emails back to the website owner when a user submits the form. All of the code used in the process will be provided and explained as required.
Laravel provides a Mail API that enables users to take advantage of the Swift Mailer library to send emails by integrating it with an external SMTP provider like Gmail, Mailtrap, etc. Dedicated email service providers such as Mailgun and Amazon SES can also be used.
Ok, let’s get started.
Start by creating a new Laravel application
Go to your terminal or command prompt and enter this command:
Laravel new project-name
Or this command:
composer create-project --prefer-dist laravel/laravel project-name
Then navigate (change directory) into your project directory.
Configure the mailer
To be able to send emails, we have to set up the email sender. For this tutorial, we will be using Mailtrap to configure our mailer.
Mailtrap is a dummy SMTP server that enables you to test email sending using fake SMTP information during development. It’s not to be used for production.
If you don’t have an account with Mailtrap yet, you can sign up for a free account on their website (link above).
Once you have gotten your dummy SMTP credentials from Mailtrap, go to your .env file (the .env file is located in your project folder).
Locate the email section and set up your mailer with the fake SMTP information you got from Mailtrap. Again, don’t forget to replace this with live SMTP data before moving your code to production.
The relevant section of your .env should now look like this:
123456MAIL_DRIVER=smtpMAIL_HOST=smtp.mailtrap.ioMAIL_PORT=2525MAIL_USERNAME=e7********01f*MAIL_PASSWORD=91********86c*MAIL_ENCRYPTION=nullNote: If you are pushing your application to production, then in addition to supplying your real SMTP information, you will also need to enter your real email address in the config/app.php file of your application. So, your config/app.php file should contain a line like this:
1'support' = env('SUPPORT_MAIL', 'real_email_address@gmail.com')Now let’s work on the actual contact form that the user sees
Before creating the contact form, we first want to create a master file that holds our CSS and JavaScript links. This is to avoid cluttering your actual contact form with HTML tags.
Since we’re working with both Bootstrap and jQuery, our master file includes references to both.
File path: resources/views/layouts/master.php
12345678910111213141516<!DOCTYPE html><html><head><title>Feedback Contact Form With Email Notification</title><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"/></head><body><div class="container">@yield('content')</div><script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script></body></html>With the master file done, let’s create the contact form.
Go to your view folder and create a blade. Your new blade will contain the code below.
File path: resources/views/form/contact.blade.php
123456789101112131415161718192021222324252627282930313233343536373839404142@extends('layouts.master')@section('title', 'Contact Form')@section('content')<nav class="navbar navbar-expand-lg navbar-light bg-light"><a class="navbar-brand" href="#" rel="nofollow">Contact</a></nav><br />@if(session()->has('message'))<div class="alert alert-success">{{ session()->get('message') }}</div>@endif@if ($errors->any())<div class="alert alert-danger"><ul>@foreach ($errors->all() as $error)<li>{{ $error }}</li>@endforeach</ul></div>@endif<form action="{{ route('send.message') }}" method="POST">@csrf<div class="form-group"><label for="name">Name</label><input type="text" name="name" class="form-control"/></div><div class="form-group"><label for="email">Email address</label><input type="email" name="email" class="form-control"/></div><div class="form-group"><label for="message">Message</label><textarea class="form-control" name="message" rows="3"></textarea></div><button type="submit" class="btn btn-primary">Send</button></form>@stopCreate your Routes
Routes allow you to map a request to its appropriate controller and return a view from the resources/views folder.
File path: Route/web.php
12Route::get('/contact', 'ContactController@create');Route::post('/contact', 'ContactController@store')->name('send.message');Create your functions
We will be creating two functions.
The
create()
function returns a view that will display the form on the browser. And thestore()
function will hold the validation rule and instantiate a mail class that interacts with the mailer.These functions will be created inside the ContactController file.
Navigate to your terminal and type in this command to create your controller:
php artisan make:controller ContactController -r
To avoid going back and forth we will import our mail class right away, even though the class has not been created yet.
File path: app/Http/Controllers/ContactController.php
1234567891011121314151617181920212223242526272829303132333435363738<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\Mail\ContactMail;class ContactController extends Controller{/*** Show the form for creating a new resource.** @return \Illuminate\Http\Response*/public function create(){return view('form.contact');}/*** Store a newly created resource in storage.** @param \Illuminate\Http\Request $request* @return \Illuminate\Http\Response*/public function store(Request $request){$validatedData = $request->validate(['name' => 'required','email' => 'required|email','message' => 'required']);\Mail::to('example@example.com')->send(new ContactMail($validatedData));return redirect()->back()->with('message', 'Message sent!');}}The validation rule within the
store()
function prevents the user from submitting an empty form.Notice that our destination email address is hardcoded inside the
to()
method. A better way of doing this is declaring it inside your app.php file.Go to your
config/app.php
file and add this code.123456789/*|--------------------------------------------------------------------------| Support Email|--------------------------------------------------------------------------|| This support mail address is sent with every email for feedback.|*/'support' => env('SUPPORT_MAIL', 'example@example.com'),This way, if there are other places you want to use the email address, you now have a central place where you can access it.
Declaring your SUPPORT_MAIL email address within the app.php file is optional. But if you decide to go that route, then you will need to modify the
store()
function of your ContactController.php file. To do that, go to thestore()
function and replace this line:1\Mail::to('example@example.com')->send(new ContactMail($validatedData));With this line:
1\Mail::to(config('app.support')->send(new ContactMail($validatedData));Next, create a mail class
Proceed to your terminal and enter this command:
php artisan make:mail ContactMail –markdown=email.contactMail
This command will create an email folder containing a contactMail.php blade. The markdown flag used in the above command determines the format of the email that gets sent out. Emails can be sent in plain text format, HTML format, or (as in this case), markdown format.
The name of our mail class must match the one we previously imported in the controller above.
Each email is sent through a Mailable class that contains a
build()
method. Inside thebuild()
method, we will call themarkdown()
method for email delivery.File path: app\Mail\ContactMail.php
12345678910111213141516171819202122232425262728293031323334<?phpnamespace App\Mail;use Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Mail\Mailable;use Illuminate\Queue\SerializesModels;class ContactMail extends Mailable{use Queueable, SerializesModels;public $validatedData;/*** Create a new message instance.** @return void*/public function __construct($validatedData){$this->validatedData = $validatedData;}/*** Build the message.** @return $this*/public function build(){return $this->markdown('email.contactMail');}}Now, go to the email folder and modify the contactMail blade. By default, the blade will contain this code:
File path: email/contactMail.blade.php
123456789101112@component('mail::message')# IntroductionThe body of your message.@component('mail::button', ['url' => ''])Button Text@endcomponentThanks,<br />{{ config('app.name') }}@endcomponentReplace the above with this code:
1234567891011121314@component('mail::message')## *New Mail!*@component('mail::panel'){{$validatedData['name']}},{{$validatedData['email']}}{{$validatedData['message']}}@endcomponentThanks.@endcomponentWe’re now done building. Let’s test out the form…
Testing our contact form
To test the contact form, go to the contact page in your browser and try submitting an empty form.
If your view looks like the one above then you are on track.
Now, go ahead and fill the form and resubmit.
After submission, your view should look like the one below.
Now go to your Mailtrap account to check the email. Or if you used live SMTP data, check your email in your email provider’s portal/tool/app.
And you are done!
Hope this article was helpful to you.
You can drop your feedback, comments, or challenges using the replies section below.
- AuthorPosts
- You must be logged in to reply to this topic.