在 Laravel 中插入数据到包含单选按钮的表单,通常涉及到以下几个步骤:
<!-- resources/views/your_form.blade.php -->
<form action="{{ route('submit.form') }}" method="POST">
@csrf
<label>
<input type="radio" name="option" value="option1"> Option 1
</label>
<label>
<input type="radio" name="option" value="option2"> Option 2
</label>
<button type="submit">Submit</button>
</form>
// routes/web.php
Route::post('/submit-form', [YourController::class, 'submitForm'])->name('submit.form');
// app/Http/Controllers/YourController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class YourController extends Controller
{
public function submitForm(Request $request)
{
$validatedData = $request->validate([
'option' => 'required',
]);
// 插入数据到数据库
$data = new YourModel();
$data->option = $validatedData['option'];
$data->save();
return redirect()->back()->with('success', 'Data inserted successfully!');
}
}
// app/Models/YourModel.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class YourModel extends Model
{
protected $fillable = ['option'];
}
validate
方法中的验证规则,确保所有必填字段都已填写;检查数据库连接配置,确保数据库连接正常。@csrf
指令,或在路由中禁用 CSRF 保护。通过以上步骤,你可以在 Laravel 中成功插入包含单选按钮的数据。
领取专属 10元无门槛券
手把手带您无忧上云