Search code examples
laravelforms

Laravel handling one contact form for all pages


The typical way of handling the contact form is in the contact page and the route can be:

Route::get('/contact', 'App\Http\Controllers\PageController@contact')->name('contact');
Route::post('/contact', 'App\Http\Controllers\PageController@formContact')->name('form.contact');

The PageController using the formContact method will handle the validation of the form and can be submitted fine.

What happens if the contact form is included on all pages? Let's say it's included in the footer. How can I handle that form?

This is the contact form:

<div class="form-contact">
  <div class="container">
    <div class="row">
      <h2>Contact form</h2>
      <div class="col-sm-8">
        <form action="" method="POST">
          @csrf
          <div class="row">
            <div class="col-sm-6">
              <div class="mb-4">
                <input type="text" name="first_name" placeholder="First name*" class="form-control" />
              </div>
            </div>
            <div class="col-sm-6">
              <div class="mb-4">
                <input type="text" name="last_name"  placeholder="Last name*" class="form-control" />
              </div>
            </div>
            <div class="col-sm-6">
              <div class="mb-4">
                <input type="text" name="phone"  placeholder="Phone*" class="form-control" />
              </div>
            </div>
            <div class="col-sm-6">
              <div class="mb-4">
                <input type="text" name="email"  placeholder="Email*" class="form-control" />
              </div>
            </div>
            <div class="col-sm-12">
              <div class="mb-4">
                <textarea rows="8" placeholder="Text*" class="form-control"></textarea>
              </div>
            </div>
            <div class="col-sm-12">
              <button type="submit" class="btn btn-purple">Submit</button>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

This is the footer:

<footer>
  @include('includes.form-contact')
</footer>

When the contact form is not only on one single page but all pages, which controller and method can I use?


Solution

  • There's no need to figure out on which page should be using the route, as that form is already included. The only needed thing here is the second route that uses the post and formContact method.

    Route::post('/contact', 'App\Http\Controllers\PageController@formContact')->name('form.contact');