简体   繁体   中英

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.

Here is the example of that:-

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

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

Please make sure APP_KEY in .env file is not blank. If it is blank then run "php artisan key:generate" to generate that. After setting APP_KEY all will work fine.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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