The Laravel contact form send email tutorial will share with you how to create Contact Us Form in Laravel with Email Sending Example. We will use form validation, storing data in the database, email sending and success message.
Contact Us form is a widely used feature required by almost every web or mobile application. Laravel offers built-in features to easily create a contact form that sends email using the Mail class. Let’s see the below step by step to add a contact us form and save data to the database then send email that user.
Laravel Contact Form with Email Send Example
Follow the following steps to integrate the contact us form with email send example in laravel apps.
- Step 1: Install Laravel App
- Step 2: Setup Database
- Step 3: Generate Model And Migration
- Step 5: Make Routes
- Step 6: Create Controller
- Step 8: Create Blade Views
- Step 9: Sending Email
- Step 10: Run Your app
1. Install Laravel App
First of all, open your terminal and execute the following command to install or download fresh laravel app.
composer create-project --prefer-dist laravel/laravel contact-us
2. Setup Database Credentials
After that, open the “.env” file and update the database name, username and password in the env file.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=homestead // your database name DB_USERNAME=homestead // your database username DB_PASSWORD=secret // your database username
3. Create Model and Migration
In this step, execute the following command on the terminal to create contacts table migration and create Contact Modal:
php artisan make:model Contact -m
Open database/migrations/2019_09_02_161223_create_contacts_table.php file and add the database columns same as below.
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateContactsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('contacts', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email'); $table->string('phone_number')->nullable(); $table->string('subject')->nullable(); $table->text('message'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop("contacts"); } }
Next, run the migration using the below command.
php artisan migrate
Now you can check in your database to create a new table named as contacts with given columns.
4. Make Routes
Next, open your “routes/web.php” file and add the following route to create a contact form with email sending example.
use App\Http\Controllers\ContactController;
Route::get('/contact-us', [ContactController::class, 'index']);
Route::post('/contact-us', [ContactController::class, 'save'])->name('contact.store');
5. Create Controller
In this step, open your terminal and execute the following command to create the ContactController.php file:
php artisan make:controller ContactController
Next, go to app/http/controller/ContactController.php. and update the following code on it.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Contact; use Mail; class ContactController extends Controller { public function index() { return view('contact-us'); } public function save(Request $request) { $this->validate($request, [ 'name' => 'required', 'email' => 'required|email', 'subject' => 'required', 'phone_number' => 'required', 'message' => 'required' ]); $contact = new Contact; $contact->name = $request->name; $contact->email = $request->email; $contact->subject = $request->subject; $contact->phone_number = $request->phone_number; $contact->message = $request->message; $contact->save(); return back()->with('success', 'Thank you for contact us!'); } }
6. Create Blade File
In this step, go to the resources/views directory and create a new file named as contact-us.blade.php.
Next, open the resources/views/contact-us.blade.php file and update the below code on it.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Laravel 5.8 CRUD Example Tutorial</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="content"> <div class="row"> <div class="col-md-12"> <div class="card card-user"> <div class="card-header"> <h5 class="card-title">Contact Us</h5> </div> <div class="card-body"> @if(Session::has('success')) <div class="alert alert-success"> {{ Session::get('success') }} </div> @endif <form method="post" action="contact-us"> {{csrf_field()}} <div class="row"> <div class="col-md-12"> <div class="form-group"> <label> Name </label> <input type="text" class="form-control @error('name') is-invalid @enderror" placeholder="Name" name="name"> @error('name') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="col-md-12"> <div class="form-group"> <label> Email </label> <input type="text" class="form-control @error('email') is-invalid @enderror" placeholder="Email" name="email"> @error('email') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="col-md-12"> <div class="form-group"> <label> Phone Number </label> <input type="text" class="form-control @error('phone_number') is-invalid @enderror" placeholder="Phone Number" name="phone_number"> @error('phone_number') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="col-md-12"> <div class="form-group"> <label> Subject </label> <input type="text" class="form-control @error('subject') is-invalid @enderror" placeholder="Subject" name="subject"> @error('subject') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="col-md-12"> <div class="form-group"> <label> Message </label> <textarea class="form-control textarea @error('message') is-invalid @enderror" placeholder="Message" name="message"></textarea> @error('message') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> </div> <div class="row"> <div class="update ml-auto mr-auto"> <button type="submit" class="btn btn-primary btn-round">Send</button> </div> </div> </form> </div> </div> </div> </div> </div> </div> </body> </html>
7. Create Contact Email Blade File
Next, create another blade file contact_email.blade.php. This file content show in your mail inbox. Now open the resources/views/contact_email.blade.php file and upadte the following code on it.
<h2>Hello Admin,</h2> You received an email from : {{ $name }} Here are the details: <b>Name:</b> {{ $name }} <b>Email:</b> {{ $email }} <b>Phone Number:</b> {{ $phone_number }} <b>Subject:</b> {{ $subject }} <b>Message:</b> {{ $user_message }} Thank You
8. Configuring Email server
In this step, we are going to configure the MailTrap SMTP server in Laravel. Firstly you need to create an account in mailtrap.io.
Login to your mailtrap account and go SMTP setting copy username and password details and add in your .env file just seeding below.
MAIL_DRIVER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=587 MAIL_USERNAME=331e7######### Your mailtrap username MAIL_PASSWORD=25a10#########Your mailtrap password MAIL_ENCRYPTION=tls
9. Sending Email in Laravel
So after configuring all your Laravel contact page, you need to add the below code in your ContactController after save button. In bellow, we have added the mail function where you could easily send the user details to mailtrap.
\Mail::send('contact_email', array( 'name' => $request->get('name'), 'email' => $request->get('email'), 'subject' => $request->get('subject'), 'phone_number' => $request->get('phone_number'), 'user_message' => $request->get('message'), ), function($message) use ($request) { $message->from($request->email); $message->to('admin@example.com'); });
Step 10: Update Controller Using Mail Function
If you have not idea to how to add mail function in your controller, don’t worry we added the here below check how to add the mail function after data storing. This is updated controller to sending mail after creating contact form in laravel.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Contact; use Mail; class ContactController extends Controller { public function index() { return view('contact-us'); } public function save(Request $request) { $this->validate($request, [ 'name' => 'required', 'email' => 'required|email', 'subject' => 'required', 'phone_number' => 'required', 'message' => 'required' ]); $contact = new Contact; $contact->name = $request->name; $contact->email = $request->email; $contact->subject = $request->subject; $contact->phone_number = $request->phone_number; $contact->message = $request->message; $contact->save(); \Mail::send('contact_email', array( 'name' => $request->get('name'), 'email' => $request->get('email'), 'subject' => $request->get('subject'), 'phone_number' => $request->get('phone_number'), 'user_message' => $request->get('message'), ), function($message) use ($request) { $message->from($request->email); $message->to('admin@example.com'); }); return back()->with('success', 'Thank you for contact us!'); } }
Learn Also: Send Mail in PHP from Contact Us Using PHPMailer
I hope you liked our post, feel free to share and let us know in the comment box if you have any questions.
Failed to authenticate on SMTP server with username “raomyousaf@gmail.com” using 3 possible authenticators. Authenticator CRAM-MD5 returned Expected response code 235 but got code “535”, with message “535 5.7.0 Invalid login or password
“. Authenticator LOGIN returned Expected response code 250 but got an empty response. Authenticator PLAIN returned Expected response code 250 but got an empty response.
Its your mailtrap issue.
Thanks for your explaining
$message->from( $request->email ); This is not wokring In Gmail come MAIL_USERNAME :/ What problem ?
Thank you for this explanation. It worked, but using the port=587 and MAIL_ENCRYPTION=tls.
Btw, it can be very helpful if you run this command just in case: php artisan config:cache.
when i run this code i got an error like this
message: “Connection could not be established with host smtp.mailtrap.io :stream_socket_client(): unable to connect to tcp://smtp.mailtrap.io:587 (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
↵)”
plz resolve the problem
Thanks a lot. Everything works just fine. Just what I needed.
If there is a validation error, have to fill in the form again when return. How to return the value to the form?
Use old value.
hlo
adsf
Hi I have a problem when I write my contact email to my mail like : ()->from($request->email) it doesn’t get a custom email it get a .env email
Please any help.
Hi everything works just fine except I get the email in mailtrap account and not my email address. the recipient address according to my mailtrap account is just fine. what could be the issue
we provide consulting for our sap clientele , we wish to develop interfaces and libraries with your product
Thanks!
Ya