如何在Laravel框架中获取textarea的内容与值?
How to Get Textarea Content in Laravel
Hey there! Let's break down how to properly retrieve the value of a textarea in your Laravel setup, based on the code and config you shared.
Step 1: Verify Your View Setup
First, make sure your admin.blade.php view has a properly configured form and textarea:
- The form should use the
POSTmethod and point to your route. - Include Laravel's CSRF token (this is mandatory to avoid 419 errors).
- Your textarea must have the correct
nameattribute matching what you're trying to fetch (in your case,compr).
Here's what that might look like in your view:
<form method="POST" action="{{ route('sname') }}"> @csrf <textarea name="compr" id="compr" rows="6" placeholder="Enter your content..."></textarea> <button type="submit">Submit</button> </form>
Step 2: Retrieve the Value in Your Controller
While using $_POST['compr'] technically works, Laravel provides a more secure, framework-friendly way using the Request class. This approach also makes validation and error handling easier.
Update your GeneralController.php like this:
use Illuminate\Http\Request; class GeneralController extends Controller { public function Sname(Request $request) { // Option 1: Get the value directly using the input() method $comprContent = $request->input('compr'); // Option 2: Shorthand using property access $comprContent = $request->compr; // Optional: Add validation to ensure the content is present $validatedData = $request->validate([ 'compr' => 'required|string', // Adjust rules as needed ]); $comprContent = $validatedData['compr']; // Now you can use $comprContent for whatever you need (store, process, etc.) return back()->with('success', 'Content received successfully!'); } }
Step 3: Tweak Your Route (Optional but Recommended)
Your existing route works, but adding a name makes it easier to reference in your view (like we did with route('sname') above):
Route::post('sname', 'GeneralController@Sname') ->middleware(['auth','admin:6']) ->name('sname');
Key Notes
- Always include the
@csrfdirective in your POST forms—Laravel blocks requests without it by default. - Using the
Requestclass gives you access to Laravel's validation, error messaging, and other helpful features that raw$_POSTdoesn't provide. - If you still want to use
$_POST, double-check that your form is correctly submitted and the CSRF token is present (otherwise you'll get a 419 error).
内容的提问来源于stack exchange,提问作者Seirid
相关产品推荐
相关产品推荐

