DEV Community

faisal ahmed
faisal ahmed

Posted on

Laravel 11 : Custom package does not generate CSRF token.

I encountered this problem while trying to generate csrf token in form on a laravel 11 based custom package.

The routes in my custom package already included the default web middleware but still it was not generating the needed csrf token for routes and views which belonged to the custom laravel package.

The solution was to include StartSession and VerifyCsrfToken middleware manually inside the app.php file to be used as a global middleware.

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->append(\Illuminate\Session\Middleware\StartSession::class);
        $middleware->append(\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
xwero profile image
david duymelinck

Why not bind the middleware on the route level, either on a group or on the form route?

This keeps all the functionality inside your custom package.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs