简体   繁体   中英

Laravel package session variable not saving with ajax call

I'm building a package called under-construction . When this package is activated in a config file the site will be underconstruction only people with the right code can access the application.

https://github.com/larsjanssen6/underconstruction

The problem that I have right now:

When the code is entered I make an ajax call that hit's this controller method (called check ):

https://github.com/larsjanssen6/underconstruction/blob/master/src/Controllers/CodeController.php

If the code is correct a session variable is being set:

session(['can_visit' => true]);

Then in my vue.js code I redirect to / . And it will hit my middleware again. Here I check if a session called can_visit exists.

return session()->has('can_visit');

https://github.com/larsjanssen6/underconstruction/blob/master/src/UnderConstruction.php

But the session variable can_visit is always gone! How is that possible?

Thanks for your time.

You're not loading the session middleware, so session is not started and no values are persisted.

As was mentioned in the comments, even though your protected routes ( / ) are within the web middleware (read session), your service provider's routes ( /under/construction , /under/check ) are not (no write session).

The simple fix is to add the session, or even better, the whole web middleware.

$routeConfig = [
    'namespace' => 'LarsJanssen\UnderConstruction\Controllers',
    'prefix' => 'under',
    'middleware' => [
        'web', // add this
        // DebugbarEnabled::class, // leaving this dead code behind despite vcs
    ],
];

However, you might quickly run into trouble with infinite redirect loops if a user adds your middleware to their web middleware group. So I would add a check of some sort to make sure you're not on one of the existing underconstruction routes.

public function handle($request, Closure $next)
{
    // check this isn't one of our routes
    // too bad router hasn't loaded named routes at this stage in pipeline yet :(
    // let's hope it doesn't conflict with user's routes
    if ($request->is('under/*')) {
        return $next($request);
    }

    if (! $this->config['enabled']) {
        return $next($request);
    }

    if (!$this->hasAccess($request)) {
        return new RedirectResponse('/under/construction');
    }

    return $next($request);
}

And ultimately guessing from the context of this project, I'd expect most people would want to stick this in the global middleware. However, you're going to run into the same session-hasn't-started-yet issues because that doesn't run in the global middleware. So there's more to chew on. Happy coding!

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