Laravel Basic
Laravel Form
Laravel Database
Laravel Advance
Forms are the entry point for user input in web applications.
Laravel makes handling forms easier by providing built-in CSRF protection, validation, old input handling, and request data binding.
You can create a form using HTML or with Blade components/packages.
// routes/web.php use App\Http\Controllers\ContactController; Route::get('/contact', [ContactController::class, 'index'])->name('contact.form'); Route::post('/contact', [ContactController::class, 'store'])->name('contact.submit');
// app/Http/Controllers/ContactController.php namespace App\Http\Controllers; use Illuminate\Http\Request; class ContactController extends Controller { public function index() { return view('contact'); } public function store(Request $request) { // Validation $request->validate([ 'name' => 'required|string|max:100', 'email' => 'required|email', 'message' => 'required|min:10', ]); // Store or send email // Contact::create($request->all()); return back()->with('success', 'Message sent successfully!'); } }
<!-- resources/views/contact.blade.php --> <form action="{{ route('contact.submit') }}" method="POST"> @csrf <!-- CSRF protection --> <label for="name">Name:</label> <input type="text" name="name" value="{{ old('name') }}"> <label for="email">Email:</label> <input type="email" name="email" value="{{ old('email') }}" > <label for="message">Message:</label> <textarea name="message">{{ old('message') }}</textarea> <button type="submit">Send</button> </form> <!-- Displaying Validation Errors --> @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif
Laravel automatically keeps input values when validation fails:
<input type="text" name="name" value="{{ old('name') }}">
Every form must include @csrf
:
<form method="POST" action="/submit"> @csrf ... </form>
Without CSRF token, Laravel will throw 419 Page Expired
.
<form action="{{ route('upload.file') }}" method="POST" enctype="multipart/form-data"> @csrf <input type="file" name="profile_picture"> <button type="submit">Upload</button> </form>
public function upload(Request $request) { $request->validate([ 'profile_picture' => 'required|image|mimes:jpg,png,jpeg|max:2048', ]); $path = $request->file('profile_picture')->store('uploads', 'public'); return back()->with('success', 'File uploaded at ' . $path); }