Laravel

Using Forms and Gathering Input

Using Forms and Gathering Input in Laravel

Building interactive web applications means accepting and processing user input — and Laravel makes handling forms secure, simple, and powerful.

In this post, you’ll learn:

  • How to create HTML forms in Laravel views

  • Handling form submission in controllers

  • Validating user input

  • Using old input and error messages

  • Protecting forms with CSRF tokens


️ Creating a Basic Form in Blade

Here’s a simple example of a form that collects a user’s name and email:

blade
<form action="{{ route('user.store') }}" method="POST">
@csrf

<label for="name">Name:</label>
<input type="text" id="name" name="name" value="{{ old('name') }}" required>

<label for="email">Email:</label>
<input type="email" id="email" name="email" value="{{ old('email') }}" required>

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

  • @csrf adds a Cross-Site Request Forgery token to protect your form

  • old('field') repopulates the input after validation errors


Setting Up the Route

In your routes/web.php:

php
use App\Http\Controllers\UserController;

Route::post('/user', [UserController::class, 'store'])->name('user.store');


Handling Form Submission in Controller

In UserController.php:

php
use Illuminate\Http\Request;

public function store(Request $request)
{
// Validate input
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users,email',
]);

// Process data (e.g., save to database)
// User::create($validated);

return back()->with('success', 'User registered successfully!');
}


⚠️ Validation and Error Handling

Laravel’s $request->validate() automatically redirects back with errors if validation fails.

Display errors in your Blade view:

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

✅ Best Practices

  • Always use @csrf to protect forms

  • Validate user input rigorously

  • Use old() to keep input after errors

  • Display user-friendly error messages

  • Sanitize and escape output when displaying data


Wrapping Up

Handling forms and user input is essential for any Laravel app. By using Blade forms, controllers, and built-in validation, you ensure your app is secure, robust, and user-friendly.

Leave a Reply

Your email address will not be published. Required fields are marked *