kundefine
4 months ago
65
10
Laravel

get dynamic csrf token

Posted 4 months ago by kundefine

Test Model:

class Test extends Model
{
    
    public static function myForm() {
        $output = '';
        $output .= '<form action="/url" method="post">';
        $output .= csrf_field();
        $output .= '<input type="text">';
        $output .= '</form>';

        return $output;
    }
}

TestController

class TestController extends Controller
{
    public function index() {
        return view('test.view');
    }
}

AppServiceProvider

use App\Test;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $myForm = Test::myForm();
        view()->share('myForm', $myForm);
    }

}

view.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  {!! $myForm !!}
</body>
</html>

output

<form action="/url" method="post">
    <!-- Here is the problem -->
    <!-- where is the CSRF TOKEN value -->
    <input type="hidden" name="_token" value=""> 
    <input type="text">
</form>

if you check my code you will understand what i am trying to say,

Please sign in or create an account to participate in this conversation.