blog banner alt

How to Make a Contact Page in Laravel 5.4 in Three Simple Steps

Last updated Apr 14, 2017


Making a contact page that allows you to receive mails seems a little daunting, but with laravel 5.4 it is a very simple process!

Following this post, you will be able to easily make your own contact page and with the least amount of code you have to write.

(In less than 10 minutes)

so, let's get started!

Today, we're using Laravel 5.4  Notification and Form Request Object components, to make a contact page like this:

A laravel contact form
Figure 1: Contact form Made with Laravel 5.4

 

Step 1: Create the Essentials

First, what are the basics we need to make this page?

  • Contact page controller for displaying the page and mail to admin
  • Form request class consist of validation rules
  • Notification class that handles the incoming mail
  • Model class that uses the notifiable trait stores the admin info
  • configuring Larevel .env mail settings
  • Define the Routes
  • View to render the page

Okay, let’s create first four classes using Laravel’s Artisan command:

Controller:

$ php artisan make:controller ContactController

Form Request Class:

$ php artisan make:request ContactFormRequest

Notification Class:

$ php artisan make:notification InboxMessage

Model Class:

$ php artisan make:model Admin

 

Then in laravel's .env, you want to add your email driver and credantials.

In this tutorial, we will be using gmail, but if you want to use an API mail driver like Mailgun, be sure to check out my tutorial on Sending Emails with Maigun in Laravel.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=yourpassword
MAIL_ENCRYPTION=ssl 

 

Good job! Now we will need to define the route:

In routes/web.php, let’s add the following two routes, one for GET to display the form, another for POST to send the message:

Route::get('/contact', '[email protected]');
Route::post('/contact',  '[email protected]'); 

 

Finally, with the view, you will need to go to your /resources/views directory and create file, in this tutorial we will call it contact.blade.php.

 

Step 2: Populate the Classes

Controller

We will need these two methods:

  • show() that handles the GET request for displaying the form
  • mailToAdmin() to POST the message to the website admin

This is how we want the controller to look like:

Namespace App\Http\Controllers;

use App\Notifications\InboxMessage;
use App\Http\Controllers\Controller;
use App\Http\Requests\ContactFormRequest;
use App\Admin;

Class ContactController extends Controller
{
	public function show() 
	{
		return view('contact');
	}

	public function mailToAdmin(ContactFormRequest $message, Admin $admin)
	{        //send the admin an notification
		$admin->notify(new InboxMessage($message));
		// redirect the user back
		return redirect()->back()->with('message', 'thanks for the message! We will get back to you soon!');
	}
}

Notice how we need a form request object and an Admin model object for the mailToAdmin() method?

Okay, now we can make these two classes functional!

 

Request Form Class

As the name implies, ContactFormRequest will be in charge of handling the form request rules.

In App/Http/Requests/ContactFormRequest.php, we will need to change the return value in authorize() to true, and add the rules to the rules() method which is already provided for you, like so:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ContactFormRequest extends FormRequest
{
  
    public function authorize()
    {
        return true;
    }

 
    public function rules()
    {
        return [
            'name' => 'required|max: 255',
            'email' => 'required|email|max: 255',
            'message' => 'required',
        ];
    }
}

 

Admin Model Class:

For the admin information such as name and email address, I propose creating a dedicated file in the config directory for flexibility and reusability.

So we will create the file config/admin.php:

Return [
   
    'email' => '[email protected]',
    'name' => 'your_name',
     
];

And yes! You can use any email address you want to receive messages from the contact form!

 

In order for the Admin object to be available to access notify() method, we will need to import the Notifiable trait provided by Laravel:

namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;

class Admin extends Model
{
    use Notifiable;

    protected $admin;
    protected $email;
	
    public function __construct() {
        $this->admin = config('admin.name');
        $this->email = config('admin.email');
    }
}

 

Notification:

If you are not yet familiar with Notifications, don’t worry, it’s very simple!

 

You can find the notification class we created with artisan command in App/Notifications directory, you will see many methods are already there.

In our App/Notifications/InboxMessage.php, we just need to change a few things.

 

First, Import our ContactFormRequest in the beginning of the file:

use App\Http\Requests\ContactFormRequest;

Then add a protected property and pass to the constructor methods, this property should be an object of ContactFormRequest:

protected $message;
    public function __construct(contactFormRequest $message)
    {
        $this->message = $message;
    }

Finally, we want to populate our mail message in the toMail() Method!

public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->subject(config('admin.name') . ", you got a new message!")
                    ->greeting(" ")
                    ->salutation(" ")
                    ->from($this->message->email, $this->message->name)
					->line($this->message->message);
    }

Notice how to pass space to both greeting() and salutation() methods?

This is because Laravel Notifications comes with default messages for salutation and greeting, which are specifically for outbound mails. In this case, we want to override them to nothing for inbound mails.

 

Step 3: Make the Routes and the View

Now we have made all the necessary “backend” stuff.

let’s make this available to the users!

To do this, we will need to make the HTML template.

 

Get A boilerplate!

Generally, for views you want to have a master layout template, which is the boilerplate for your website.

If you have already have a master layout template, click here to skip.

We will create another blade template file called layout.blade.php:

<!DOCTYPE html>
<html lang="{{ config('app.locale') }}">
<head> 
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge"> 
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<!-- CSRF Token -->
	<meta name="csrf-token" content="{{ csrf_token() }}">

	<title>{{ config('app.name') }}</title>
	<!-- Styles -->
	<link href="/css/app.css" rel="stylesheet">
	
	<!-- Scripts -->
	<script>
		window.Laravel = {!! json_encode([
		'csrfToken' => csrf_token(),
		]) !!};
	</script>
	<script src="/js/app.js"></script>
</head>
	
<body>
@yield('content')
</body>

Note: If you have not used Laravel Mix to pull in Bootstrap and jquery, please replace the <link> and the <script> tag that are currently referencing css/app.css and /js/app.js, to respective path of these resources.

 

For reference:

 

Contact Page View

As we have created the file contact.blade.php in step one, let’s add the HTML content on to it!

However, you can design your contact page however you want, the code below allows you to make a basic contact form.

In the /resource/views/contact.blade.php:

@extends('layout')

@section('content')
<div class="container">
	<h1 class="mb-2 text-center">Contact Us</h1>
	
	@if(session('message'))
	<div class='alert alert-success'>
		{{ session('message') }}
	</div>
	@endif
	
	<div class="col-12 col-md-6">
		<form class="form-horizontal" method="POST" action="/contact">
			{{ csrf_field() }} 
			<div class="form-group">
			<label for="Name">Name: </label>
			<input type="text" class="form-control" id="name" placeholder="Your name" name="name" required>
		</div>

		<div class="form-group">
			<label for="email">Email: </label>
			<input type="text" class="form-control" id="email" placeholder="[email protected]" name="email" required>
		</div>

		<div class="form-group">
			<label for="message">message: </label>
			<textarea type="text" class="form-control luna-message" id="message" placeholder="Type your messages here" name="message" required></textarea>
		</div>

			<div class="form-group">
				<button type="submit" class="btn btn-primary" value="Send">Send</button>
			</div>
		</form>
	</div>
 </div> <!-- /container -->
@endsection

That’s it and great job! Now you can go over to your /contact page and try it out!

 

Once you send the messages on your contact page, you should be receiving an email in your inbox looking like this:

A laravel contact form
Figure 2: Inbox Message Example

 

Final Note

You can also customize the design of your inbox message however you want.

All you need to do is with an artisan command:

$ php artisan vendor:publish --tag=laravel-mail

With this, you should be able to see a new directory called vendor in your resources/views.


Tags