1: Create the Form: First, create a form in your Blade view that collects user input.
Example:
<form method="POST" action="{{ route('submitForm') }}">
@csrf
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<button type="submit">Submit</button>
</form>
2: Define a Route for the Form Submission: Next, define a route in web.php
to handle the POST request when the form is submitted.
Example:
Route::post('/submit-form', [FormController::class, 'submitForm'])->name('submitForm');
3: Create the Controller Method: In the corresponding controller (e.g., FormController
), define the method to process the form data. You can use the Request
object to access form data.
Example:
use Illuminate\Http\Request;
class FormController extends Controller
{
public function submitForm(Request $request)
{
$name = $request->input('name');
return "Hello, " . $name;
}
}
4: Form Validation (Optional but Recommended): Before processing the form data, it’s a good practice to validate the input. Laravel provides an easy way to validate form data.
Example:
public function submitForm(Request $request)
{
$request->validate([
'name' => 'required|max:255',
]);
$name = $request->input('name');
return "Hello, " . $name;
}
5: Redirect After Submission: After successfully processing the form, you can redirect the user to another page or back to the form with a success message.
Example:
public function submitForm(Request $request)
{
$request->validate([
'name' => 'required|max:255',
]);
// Process the data (e.g., store in database)
return redirect()->route('formPage')->with('success', 'Form submitted successfully!');
}
6: isplay Success/Failure Messages in the View: You can display success or error messages in your Blade view by checking the session data.
Example:
@if(session('success'))
<p>{{ session('success') }}</p>
@endif
Handling form submissions in Laravel is simple and efficient. By using routes, controllers, validation, and redirecting the user as needed, you can manage form submissions securely and effectively. Always ensure to validate user input and provide feedback after submission for the best user experience.