如何在laravel中插入简单表格值?

时间:2018-10-04 12:28:20

标签: php laravel

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新手。现在,我想将表单值存储到数据库表中,但是现在,它没有发生,我不知道这段代码有什么问题。所以,请帮我解决这个问题。

谢谢

4 个答案:

答案 0 :(得分:0)

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

<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>

答案 1 :(得分:0)

您缺少的CSRF令牌添加此

{{ csrf_field() }}

答案 2 :(得分:0)

像这样在您的表单标签中添加_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>

答案 3 :(得分:0)

添加{{csrf_field()}},操作将为action =“ {{url('/ create')}}”“