skip to Main Content

The result generated by @csrf in Blade

<input type="hidden" name="_token" value="">

Also tried {!! csrf_field() !!} and {{ csrf_field() }} but still there is no value .

I know this question is already asked Laravel CSRF value empty, but the solution for that did not work for me.

app/Http/Kernel.php

'web' => [
  AppHttpMiddlewareEncryptCookies::class,
  IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
  IlluminateSessionMiddlewareStartSession::class,
  IlluminateViewMiddlewareShareErrorsFromSession::class,
  AppHttpMiddlewareVerifyCsrfToken::class,
  IlluminateRoutingMiddlewareSubstituteBindings::class,
],

2

Answers


  1. Make sure that the web middleware group, which includes the VerifyCsrfToken middleware, is applied to your routes. In your app/Http/Kernel.php file, the web middleware group should be applied to the necessary routes.

    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            // IlluminateSessionMiddlewareAuthenticateSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],
    ];
    

    after this try clearning cache of application and regenrate key

    php artisan cache:clear
    php artisan view:clear
    php artisan config:clear
    php artisan route:clear
    
    Login or Signup to reply.
  2. If you look at the code inside you will see that the csrf_token is created if a session has been created. I think this is the main reason. Check the .env file and the driver for the session. If it is a file check the permissions for the storage directory.

    Also make sure you are using web guard. Since it defaults to IlluminateSessionMiddlewareStartSession::class, or include it in your active group if it is an api or something else.

    Without a session, there will be no csrf token.

    function csrf_field()
    {
            return new HtmlString('<input type="hidden" name="_token" value=''.csrf_token().''>'');
    }
    
    function csrf_token()
    {
        $session = app('session');
    
        if (isset($session)) {
            return $session->token();
        }
    
        throw new RuntimeException('Application session store not set.');
    }
    
    

    You can check it out

    app('session')->start();
    
    dd(app('session')->token());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search