Create Form Submission from View to Controller in Laravel
Written by Saran on
January 5, 2024In 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:
<!-- 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.
// 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.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
// 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.
<!-- resources/views/myform.blade.php -->
@if(session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif