修复联系表单报错:Undefined variable: content问题求助
Hey there! Let's tackle that "Undefined variable: content" error you're seeing with your contact form. I've run into this exact issue a few times with Laravel forms, so here's what's going on and how to fix it:
What's Causing the Error?
This error means your Blade template is trying to use a variable named $content that hasn't been passed to it from your controller. Looking at your code snippet, you're using Input::old('content') (which works for retrieving previously submitted values), but somewhere else in your view file, you're probably referencing {{ $content }} directly without defining it first.
Step-by-Step Fixes
Check Your View for Direct
$contentReferences
First, look at the line number mentioned in your error message (it will tell you exactly where the undefined variable is being used). If you see something like{{ $content }}, replace it with{{ old('content') }}— this Laravel helper pulls the submitted value from the session (if validation failed) or returns an empty string on the first page load, eliminating the undefined variable issue.Updated textarea code (using the newer, recommended
old()helper instead of the deprecatedInput::old()):<textarea class="form-control textarea" rows="7" name="content" id="content" placeholder="Your Message">{{ old('content') }}</textarea>Pass the Variable from Your Controller (If Needed)
If you need to pre-fill the textarea with a default value, update your controller's GET method to send the$contentvariable to the view:public function showContactForm() { // Set a default empty string or your pre-filled content $content = ''; return view('contact', compact('content')); }For POST requests where validation fails, Laravel can automatically save the user's input to the session — just make sure you use
withInput()when redirecting back:public function submitContactForm(Request $request) { $validated = $request->validate([ 'content' => 'required|min:5', // Adjust rules to match your needs // Add validation rules for other fields here ]); // Handle message sending logic here if validation passes... // If validation fails, redirect back with errors and saved input return redirect()->back()->withErrors($validated)->withInput(); }The
withInput()method ensuresold('content')works correctly, so you don't have to manually pass the$contentvariable here.Verify Error Display Code
Your error line<span class="error">{{ $errors->first('content') }}</span>is totally fine —$errorsis automatically available in all views when validation fails, so this isn't the source of your issue.
Quick Recap
- Replace any direct
{{ $content }}calls in your view with{{ old('content') }} - If you need a default value, pass
$contentfrom your controller to the view - Use
withInput()in your POST controller method to retain user input after validation fails
That should squash that undefined variable error and get your contact form working properly!
内容的提问来源于stack exchange,提问作者H Frank

