如何在拉拉维尔中插入简单的表单值?



resources/view/index.blade.php

<html>
<head>
<title>Laravel</title>
</head>
<body>
<form method="post" action = "/create">
<input type="text" name="fname" id="fname" placeholder="firstname" /><br/><br/>
<input type="text" name="phone" id="phone" placeholder="phone" /><br/><br/>
<input type="submit" name="submit" id="submit" />
</form>
</body>
</html>

控制器

class StudInsertController extends Controller {
public function insertform()
{
return view('index');
} 
public function insert(Request $request)
{
$fname = $request->input('fname')
$phone = $request->input('phone');
$data = array('fname'=>$fname,"phone"=>$phone);
DB::table('user')->insert($data);
echo "Record inserted successfully.<br/>";
echo '<a href = "/insert">Click Here</a> to go back.';
}
} 

路线

Route::get('/', function () {
return view('index');
});
Route::get('insert','StudInsertController@insertform');
Route::post('create','StudInsertController@insert');

我是拉拉维尔的新人。现在,我想将表单值存储到数据库表中,但现在,它没有发生,我不知道这段代码有什么问题。所以,请帮助我解决这个问题。

谢谢

默认情况下,Laravel中的POST路由受CSRF保护。您必须在表单中添加令牌,以确保服务器接受 post 请求。

<form method="post" action = "/create">
@csrf <!-- This blade directive generates <input type="hidden" name="_token" value="xyz..." /> -->
<input type="text" name="fname" id="fname" placeholder="firstname" /><br/><br/>
<input type="text" name="phone" id="phone" placeholder="phone" /><br/><br/>
<input type="submit" name="submit" id="submit" />
</form>

您缺少的 CSRF 令牌添加此

{{ csrf_field() }}

像这样在表单标签中添加_token

<html>
<head>
<title>Laravel</title>
</head>
<body>
<form method="post" action = "/create">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" name="fname" id="fname" placeholder="firstname" /><br/><br/>
<input type="text" name="phone" id="phone" placeholder="phone" /><br/><br/>
<input type="submit" name="submit" id="submit" />
</form>
</body>

Add {{ csrf_field(( }}and action will be action = "{{url('/create'(}}">

最新更新