Make sure you have Laravel installed on your system. If not, you can install it via Composer using the following command:
composer create-project --prefer-dist laravel/laravel contact-form
This will create a new Laravel project named contact-form
.
Define a route to handle the display of the contact form and form submission. Open routes/web.php
and add the following route:
Route::get('/contact', 'ContactFormController@show');
Route::post('/contact', 'ContactFormController@submit');
Create a controller to handle the logic for displaying the form and processing form submissions. Run the following command to generate a controller:
php artisan make:controller ContactFormController
This will create a new controller named ContactFormController
in the app/Http/Controllers
directory.
Create a Blade view file to display the contact form. You can create a new file named contact.blade.php
in the resources/views
directory. Here's an example of the form markup using Bootstrap:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap demo</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body>
<form action="/contact" method="post">
@csrf
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" id="message" name="message" rows="5" required></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
</body>
</html>
Open the ContactFormController
and implement the show
and submit
methods to display the form and handle form submissions, respectively.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ContactFormController extends Controller
{
public function show()
{
return view('contact');
}
public function submit(Request $request)
{
// Validation logic here
// Send email or store data to database
// Redirect or return response
}
}