简体   繁体   English

获取动态CSRF令牌

[英]get dynamic csrf token

I have function that generate a form from a model. 我有从模型生成表格的功能。

Category Model: 类别模型:

public static function generateForm()
{
    $output = '';

    $output .= '<form action="/category" method="post">
                '. csrf_field() .'
                <input type="text">
                <input type="submit" value="Submit" id="">                      
            </form>';
    return $output;
}

It's not working. 没用 In my *view it's showing the hidden input token but doesn't get any value. 在我的*视图中,它显示了隐藏的输入令牌,但没有任何值。

You can pass csrf_token dynamically from view to that function html. 您可以从视图动态将csrf_token传递给该函数html。

Here is the example of that:- 这是一个例子:

Category.php Category.php

public static function generateForm($token)
{
    $output = '';

    $output .= '<form action="/category" method="post">
                <input type="hidden" name="csrf_token" value="'.$token.'">
                <input type="text">
                <input type="submit" value="Submit" id="">                      
            </form>';
    return $output;
}

Now you need to pass only parameter to this function where you are calling. 现在,您只需要将参数传递给您要调用的函数。 Like this:- 像这样:-

view.blade.php view.blade.php

{{ $category->generateForm(csrf_token()) }}

Please make sure APP_KEY in .env file is not blank. 请确保.env文件中的APP_KEY不为空。 If it is blank then run "php artisan key:generate" to generate that. 如果为空,则运行“ php artisan key:generate”以生成该文件。 After setting APP_KEY all will work fine. 设置APP_KEY之后,一切都会正常运行。

try this 尝试这个

 public static function generateForm() {

        $output = '<form action="/category" method="post">'.
                               csrf_field().
                              '<input type="text">
                              <input type="submit" value="Submit" id="">                      
                          </form>';
        return $output;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM