,可以通过以下步骤实现:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class CalculationController extends Controller
{
public function calculate(Request $request)
{
$num1 = $request->input('num1');
$num2 = $request->input('num2');
$result = $num1 + $num2;
return view('calculation.result', ['result' => $result]);
}
}
resources/views/calculation/result.blade.php
文件中创建以下内容:<!DOCTYPE html>
<html>
<head>
<title>计算结果</title>
</head>
<body>
<h1>计算结果:</h1>
<p>结果为:{{ $result }}</p>
</body>
</html>
routes/web.php
文件中添加以下代码:use App\Http\Controllers\CalculationController;
Route::post('/calculate', [CalculationController::class, 'calculate'])->name('calculate');
<!DOCTYPE html>
<html>
<head>
<title>计算器</title>
</head>
<body>
<h1>计算器</h1>
<form action="{{ route('calculate') }}" method="POST">
@csrf
<label for="num1">数字1:</label>
<input type="number" name="num1" id="num1">
<label for="num2">数字2:</label>
<input type="number" name="num2" id="num2">
<button type="submit">计算</button>
</form>
</body>
</html>
通过以上步骤,当用户在表单中输入两个数字并点击计算按钮时,表单将被提交到指定的路由,该路由将调用控制器中的计算方法,并将计算结果传递给视图文件进行显示。
领取专属 10元无门槛券
手把手带您无忧上云