Laravel Crud Contact Form Tutorial 2 (For Stupid Beginners! Anyone can follow along! If not, message me!)

Woo
6 min readAug 22, 2022

In this tutorial, we will make a simple contact form with four fields:

  • The name
  • The email
  • The subject
  • The message

Step One (of Tutorial 2): Create ContactController and Migrations

Run this command in the terminal:

php artisan make:model Contact -m -c

This will generate a model, controller and migrations. The -c flag creates the controller and the -m flag creates the migrations. You will get this message in the terminal:

Step Two: Set Up Migrations

Navigate to database/migrations folder and open the file ending in create_contacts_table.php

In that file, add the following lines of code:

$table->string(‘name’);$table->string(‘email’);$table->string(‘subject’);$table->string(‘message’);

Place it in the public function up() section as shown in below picture:

Step Three: Create a Database (Windows XAMPP example)

The next step would be to create a database that we can connect the Laravel App to. In this example, I will use XAMPP on Windows to create a database.

Let’s turn on XAMPP.

In my case, I have to connect to

http://localhost:8080/phpmyadmin/

based on my configurations. For this example, we will create a database called “stupidcontact”

Then input stupidcontact then click “create”

All right, so the database seems to have been created. Let’s now connect the database to the laravel app.

STEP FOUR: Connect Laravel App To Database

Go in your Laravel app and look for a file called .env

Configure the database like this:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=stupidcontact
DB_USERNAME=root
DB_PASSWORD=

If there is a database password set, make sure to include it.

STEP FIVE: Migrate Database

Run the following command in your terminal:

php artisan migrate

You should get the following response in your terminal:

STEP SIX: Create Contact Models

We now need to edit our Contact model to add fillable attributes.

These attributes indicate table fields that can be filled to create a new record in our database. In app->Models, find and open the Contact.php file. After the line “use HasFactory;” add the following lines of code:

protected $fillable = [
‘name’,
‘subject’,
‘email’,
‘message’
];

Overall, Contact.php looks something like this:

<?phpnamespace App\Models;use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
use HasFactory;
protected $fillable = [
‘name’,
‘subject’,
‘email’,
‘message’
];
}

STEP SEVEN: Create the ContactController File

We will create two functions in our ContactController.

First, we will create an index function which will display our contact form located at resources/views/pages/contact.blade.php

(Before that, we will delete any code performing this functionality in our PageController and our routes/web.php files).

Second, we will create a store function which we will use to store messages sent by our potential clients using the contact form into our database.

  1. Use App\Models\Contact;

First, we have to add the following line so the ContactController uses the Contact Model:

Use App\Models\Contact;

2. The ContactController code:

Please examine the ContactController code thus far:

class ContactController extends Controller
{
public function index() {
return view(‘contact’);
}
public function store(Request $request) {
$this->validate($request, [
‘name’ => ‘required’,
‘subject’ => ‘required’,
‘email’ => ‘required’,
‘message’ => ‘required’
]);
$requestData = $request->all();Contact::create($requestData);return redirect(‘contact’)->with(“status”, “Your message has been sent”);
}
}
  1. Explanation of code above:
  • The Request Object: Below code makes it abundantly clear that the store function accepts two parameters. First, the Request class. According to laravel.com, the Request class provides many methods for examining the HTTP request for your application
  • Second, the $request variable. Request just means that the variable $request must be of this very class (or any descendants of this). If it’s not, you’ll get an exception.
public function store(Request $request) {
  • Validation/Abort Code: Below code is used to validate the user’s request (Contact Form Input). It checks to see if the name, subject, e-mail and message attributes are present within the request sent by the user. If not, the request is aborted.
public function store(Request $request) {$this->validate($request, [
‘name’ => ‘required’,
‘subject’ => ‘required’,
‘email’ => ‘required’,
‘message’ => ‘required’
]);
  • Saving all data in a variable: The following code retrieves all() the data sente by a user from the Request object. The data will then be saved in the variable $requestData in the form of an array.
$requestData = $request->all();
  • Example of array: For example, the variable $requestData may receive the following array:
$requestData = [
‘name’ => ‘John’,
‘subject’ => ‘Need a translator’,
‘email’ => ‘john@example.com’,
‘Message’ => ‘Please contact me at 811 288 2929’
]
  • Storing RequestData array into a Contact Object: The following code will receive data from the $requestData array to create a Contact object which will be stored in the database.
Contact::create($requestData);
  • Redirect to success message: The last line redirects us to a success message:
return redirect(‘contact’)->with(“status”, “Your message has been sent”);

STEP EIGHT: Add Routes for Contact Form

Let’s revisit routes/web.php

Assuming you removed any routes that you created with the PageController for the Contact Form, let’s add this code to use the ContactController:

use App\Http\Controllers\ContactController;

Let’s also add these routes:

Route::get(“/contact”, [ContactController::class, ‘index’]);Route::post(“/send-message”, [ContactController::class, ‘store’]);

The first route is to show the contact form by invoking the index method.

The second route is to submit the data that was submitted via the contact form.

Your particular project may have a different set of routes, of course, but this is what my routes/web.php file looks like thus far:

<?phpuse Illuminate\Support\Facades\Route;
use App\Http\Controllers\PageController;
use App\Http\Controllers\ContactController;
Route::get(‘/’, [PageController::class, ‘index’])->name(‘home’);
Route::get(‘/faq’, [PageController::class, ‘faq’])->name(‘faq’);
Route::get(‘/about’, [PageController::class, ‘about’])->name(‘about’);
Route::get(‘/contact’, [ContactController::class, ‘index’])->name(‘contact’);
Route::post(‘/send-message’, [ContactController::class, ‘store’]);

STEP NINE: Update or Build the Contact Form In Views

The next step is to create a contact form in views. If you already have a HTML contact form template, please take a look at the following sample contact.blade.php and weave in the laravel parts into your own contact form. The laravel parts will be explained below. For now, here is the sample code:

<form method=”post” action=”/send-message”>@csrf

@if (session(‘status’))
<div class=”alert alert-success”>
{{ session(‘status’) }}
</div>
@endif
<h3 class=”text-center”>Contact form</h3>
<div class=”form-group”>
<label for=”name”>Name</label>
<input type=”text” class=”form-control” id=”name” name=”name”>
</div>
<div class=”form-group”>
<label for=”subject”>Subject</label>
<input type=”text” class=”form-control” id=”subject” name=”subject”>
</div>
<div class=”form-group”>
<label for=”email”>Email</label>
<input type=”email” class=”form-control” id=”email” name=”email”>
</div>
<div class=”form-group”>
<label for=”message”>Message</label>
<textarea class=”form-control” id=”message” rows=”5" name=”message”></textarea>
</div>
<button type=”submit” class=”btn btn-primary”>Send Message</button>
</form>

Laravel Parts Explained:

  1. CSRF: This code (@csrf) generates a CSRF (Cross-Site Request Forgery) token to protect our contact form from CSRF attacks.
@csrf

2. /send-message: In the form tag, we specified that we want to send our data using the POST method to the route “/send-message”. That is because our web.php specifies a post route for /send-message that instructs the application to invoke the store method in the ContactController class.

Route::post(‘/send-message’, [ContactController::class, ‘store’]);

3. Success Message: Obviously, the code below displays a success message once the user request is successfully received by the database. The class alert and alert-success is a bootstrap class and assumes that you are using bootstrap. You can use any CSS class you want though:

@if (session(‘status’))
<div class=”alert alert-success”>
{{ session(‘status’) }}
</div>
@endif

STEP TEN: Testing Contact Form

Finally, we get to test our Contact Form. Type the following into our terminal:

php artisan serve

Now test the contact form and check your database.

It works! Data submitted in the contact form should appear in your database.

--

--

Woo

I apologize if my medium articles are all over the place, but I am writing more to organize my thoughts and for my own learning. Maybe one day I’ll organize it.