Laravel is well known for providing multiple solutions to a problem. This is one of the main reasons for the popularity of the framework. Popular Laravel solutions cover routine functionality such as authentication, sessions, routing, and caching.
Contact Us forms are another routine functionality that is a requirement of almost every website. In this article, I am going to demonstrate how you can easily create a contact form in Laravel with email. To understand the functionality of the Laravel mail function. I suggest you read my previous article on sending emails in Laravel.
Having a contact form on your site makes it simpler for visitors to contact you directly. Laravel Contact form is a widely utilized feature required by nearly every web or mobile application. In this Laravel contact form tutorial, we’ll learn to create a contact form in Laravel utilizing the Bootstrap, CSS Framework, validate contact form utilizing Laravel built-in validation, send e-mail to admin using Mailtrap.
Install Laravel
To quickly set up a Laravel application, sign up at Cloudways for free. Login to your account and create a new server. Fill in the server and the application details, and select Laravel as your application. That’s it, you have just installed a new application within a few clicks on the Cloudways platform.
Install Form Package
To create forms in Laravel, we will use laravelcollective/html package for Form facade. In order to do that, go to your Cloudways platform and open the server tab. Launch the SSH terminal and login to your server using the Master Credentials.
Now go to the root of your application by typing the following commands.
cd applications cd applicationname/public_html composer require laravelcollective/html
After successful installation of the package, goto config/app.php file and add service provider and alias:
config/app.php 'providers' => [ .... 'Collective\Html\HtmlServiceProvider', ], 'aliases' => [ .... 'Form' => 'Collective\Html\FormFacade', ],
Configure the Database
Now that you have installed the package, the next step is database configuration. Open the Application tab in the Cloudways platform. In the application access detail, you will be able to see the database credentials for your application.
Now go to the .env file, located in the application public root folder and add the credentials there.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE= your.database.name                                                                                                                            DB_USERNAME= your.database.username                                                               DB_PASSWORD= your.database.password
Create Contact us Table Using Database Migrations
Go to the public root folder of your application and run the following command to create the database migration for creating the Contact Us model.
php artisan make:migration create_contact_us_table
Now that the migration has been created, go to database/migration/date_ create_contact_us_table.php and add the following code in it.
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateContactUsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('contactus', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email'); $table->text('message'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop("contactus"); } }
Now run the following command
php artisan migrate
Now that the migration has been created, let’s create the Contact us model.
Stop Wasting Time on Servers
Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.
Create the Model
Go to your public root folder of your application and type the following command:
php artisan make:model ContactUS
Now that you have successfully created the ContactUS model, go to app/ContactUS.php and add the following code in the file:
<?php namespace App; use Illuminate\Database\Eloquent\Model; class ContactUS extends Model { public $table = 'contactus'; public $fillable = ['name','email','message']; }
Next, I will create the route.
Create the Route
Go to routes/web.php and add the following code to the route:
Route::get('contact-us', 'ContactUSController@contactUS'); Route::post('contact-us', ['as'=>'contactus.store','uses'=>'ContactUSController@contactUSPost']);
Create the Controller
After setting the routes, I will create a controller to handle the requests from the routes. Now go to app/Http/Controllers/ContactUSController.php and add the following code in it.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\ContactUS; class ContactUSController extends Controller {    /**     * Show the application dashboard.     *     * @return \Illuminate\Http\Response     */    public function contactUS()    {        return view('contactUS');    }    /**     * Show the application dashboard.     *     * @return \Illuminate\Http\Response     */    public function contactUSPost(Request $request)    {        $this->validate($request, [        'name' => 'required',        'email' => 'required|email',        'message' => 'required'        ]);        ContactUS::create($request->all());        return back()->with('success', 'Thanks for contacting us!');    } }
Create the View
Everything is now ready, and we will now create the layout of the form.Go to resources/views/ and create a file contactUS.blade.php. Place the following code in it:
<!DOCTYPE html> <html> <head> <title>Laravel 5.4 Cloudways Contact US Form Example</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> </head> <body> <div class="container"> <h1>Contact US Form</h1> @if(Session::has('success')) Â Â Â <div class="alert alert-success"> Â Â Â Â Â {{ Session::get('success') }} Â Â Â </div> @endif {!! Form::open(['route'=>'contactus.store']) !!} <div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}"> {!! Form::label('Name:') !!} {!! Form::text('name', old('name'), ['class'=>'form-control', 'placeholder'=>'Enter Name']) !!} <span class="text-danger">{{ $errors->first('name') }}</span> </div> <div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}"> {!! Form::label('Email:') !!} {!! Form::text('email', old('email'), ['class'=>'form-control', 'placeholder'=>'Enter Email']) !!} <span class="text-danger">{{ $errors->first('email') }}</span> </div> <div class="form-group {{ $errors->has('message') ? 'has-error' : '' }}"> {!! Form::label('Message:') !!} {!! Form::textarea('message', old('message'), ['class'=>'form-control', 'placeholder'=>'Enter Message']) !!} <span class="text-danger">{{ $errors->first('message') }}</span> </div> <div class="form-group"> <button class="btn btn-success">Contact US!</button> </div> {!! Form::close() !!} </div> </body> </html>
The contact form is now functional. On submitting the form, the data will be stored in the database. I will now make the form email the information.
Now create another view, email.blade.php and add the following code in it.
You received a message from : {{ $name }} <p> Name: {{ $name }} </p> <p> Email: {{ $email }} </p> <p> Message: {{ $user_message }} </p>
Sending the Email
First, read my previous article on sending email in Laravel. Now that you have read the steps, it is time to implement the process. First, set up the basic Laravel mail function through PHP Artisan. Use the following command in the terminal:
php artisan make:mail <name of mailable>
After that, login to your Gmail account. Under My account > Sign In And Security > Sign In to Google, enable two-step verification, and then generate the app password. Next, add the app password in the  .env file with the following configurations.
MAIL_DRIVER=smtp MAIL_HOST=smtp.gmail.com MAIL_PORT=587 MAIL_USERNAME= [email protected] MAIL_PASSWORD= your.generated.app.password MAIL_ENCRYPTION=tls
Now that the configuration is done, update ContactUsController.php with the following code.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\ContactUS; use Mail; class ContactUSController extends Controller { Â Â Â public function contactUS() { return view('contactUS'); } Â Â Â /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ Â Â Â public function contactUSPost(Request $request) Â Â Â { Â Â Â Â $this->validate($request, [ 'name' => 'required', 'email' => 'required|email', 'message' => 'required' ]); Â Â Â Â ContactUS::create($request->all()); Â Â Â Â Â Â Â Mail::send('email', Â Â Â Â Â Â Â array( Â Â Â Â Â Â Â Â Â Â Â 'name' => $request->get('name'), Â Â Â Â Â Â Â Â Â Â Â 'email' => $request->get('email'), Â Â Â Â Â Â Â Â Â Â Â 'user_message' => $request->get('message') Â Â Â Â Â Â Â ), function($message) Â Â Â { Â Â Â Â Â Â Â $message->from('[email protected]'); Â Â Â Â Â Â Â $message->to('[email protected]', 'Admin')->subject('Cloudways Feedback'); Â Â Â }); Â Â Â Â return back()->with('success', 'Thanks for contacting us!'); Â Â Â } }
The contact form is now ready for deployment. It will save the data in the database and email it to the given email address as well. To test the Contact Us form, go to the application and click on launch application (remember to add /contact-us to the URL).
You Might Also Like: Create Contact Form in HTML and PHP
The Final Words
In this tutorial, I have demonstrated how to create a contact form in Laravel with the functionality of emailing the information to a prespecified email address. Sign up on Cloudways for awesome Laravel hosting and tutorials.
Shahzeb Ahmed
Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways. He is growth ambitious and aims to learn & share information about PHP & Laravel Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]