Create Form Submission from View to Controller in Laravel

In Laravel, form submissions from a view to a controller typically involve creating a form in a Blade view and defining a corresponding route and controller method. Below, I’ll guide you through the basic steps:

123456789101112131415
<!-- resources/views/myform.blade.php -->

<form method="POST" action="{{ route('submit.form') }}">
    @csrf
    <!-- Your form fields go here -->
    <label for="name">Name:</label>
    <input type="text" name="name" id="name" required>

    <label for="email">Email:</label>
    <input type="email" name="email" id="email" required>

    <!-- Add more fields as needed -->

    <button type="submit">Submit</button>
</form>

Note the @csrf directive, which includes a CSRF token. This is necessary for security.

Define a Route:

In your web.php routes file, define a route that points to the controller method handling the form submission.

12345
// routes/web.php

use App\Http\Controllers\FormController;

Route::post('/submit-form', [FormController::class, 'submitForm'])->name('submit.form');

Make sure to replace FormController with the actual name of your controller and adjust the route path as needed.

Create a Controller:

Generate a controller using the Artisan command-line tool. php artisan make:controller FormController Then, open the generated controller (app/Http/Controllers/FormController.php) and define the submitForm method to handle the form submission.

12345678910111213141516171819
// app/Http/Controllers/FormController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FormController extends Controller
{
    public function submitForm(Request $request)
    {
        // Handle form submission logic here
        $name = $request->input('name');
        $email = $request->input('email');

        // Process the form data, save to database, etc.

        return redirect()->back()->with('success', 'Form submitted successfully');
    }
}

Customize the submitForm method to suit your specific needs.

Display Success Message (Optional): You can display a success message in your view. In the example above, I used redirect()->back()->with(‘success’, ‘Form submitted successfully’). You can then display this message in your view.

1234567
<!-- resources/views/myform.blade.php -->

@if(session('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif