get dynamic csrf token

874 views Asked by At

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.

3

There are 3 answers

2
Lakhwinder Singh On

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()) }}
1
Dhananjay Kyada On

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.

0
Julius Fasema On

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