How to handle form submissions in Laravel



Image not found!!

In Laravel, handling form submissions involves creating a form in your view, defining a route to handle the form submission, and implementing the logic in a controller to process the submitted data. Here's a step-by-step guide on how to handle form submissions in Laravel:

Step 1 : Create a Form:

Start by creating a form in your Blade view using the form helper. For example:

<!-- resources/views/myform.blade.php -->
<form method="POST" action="{{ route('submit_form') }}">
  @csrf
  <!-- Your form fields go here -->
  <input type="text" name="name" />
  <button type="submit">Submit</button>
</form>

Make sure to include the @csrf directive to add a CSRF token to your form for security.


Step 2 : Define a Route:

Define a route in your web.php file (or routes file of your choice) that points to the controller method that will handle the form submission.

// routes/web.php
Route::post('/submit-form', 'FormController@submitForm')->name('submit_form');


Step 3 : Create a Controller:

Create a controller using Artisan command:

php artisan make:controller FormController

Open the generated FormController.php file and implement the logic for handling form submissions.

// app/Http/Controllers/FormController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FormController extends Controller
{
    public function submitForm(Request $request)
    {
        // Validate the form data
        $request->validate([
            'name' => 'required|string|max:255',
            // Add validation rules for other fields
        ]);

        // Process the form data
        $name = $request->input('name');
        // Process other fields as needed

        // Your logic goes here

        // Redirect or return a response
        return redirect()->route('home')->with('success', 'Form submitted successfully!');
    }
}

In the above example, the submitForm method validates the form data, processes it, and then redirects the user to a specified route with a success message.


Step 4 : Display Success or Error Messages:

In your view or layout, display any success or error messages that are flashed to the session.

<!-- resources/views/layout.blade.php -->
@if(session('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif

@if($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

This code checks for success and error messages in the session and displays them accordingly.

That's it! You've now set up a basic form submission process in Laravel. Adjust the code according to your specific requirements and form fields.



=== Happy Coding :)