Liam G
Liam G

Reputation: 597

Issue with Laravel Session / SessionID

I've been using the session in laravel to tie down unauthenticated users to quotes. But I'm running into an issue that I cannot get my head around and have a feeling it has something to do with the magic parts of Laravels back end.

Here is my code:

$session_id = session()->getId();

$booking = Booking::create([
    'trip_start_date' => $request->pickup_date,
    'trip_start_time' => $request->pickup_time,
    'token' => $session_id,
    'ip' => $request->ip(),
 ]);

 session()->put('at_token', $session_id);

But then when validating the tokens in middleware, the tokens are completely different.. as logged in my file:

AT_TOKEN       [pjIGjpuz0tRT0mjLTtdwgzTCDXrdwRCJssgJ1ukE]
BOOKING TOKEN  [3fcjAzdKTOv2IGy3Zw7skh2c9PqN9O9G98BVbAO0]

I see the token in the session looks like a session ID but the one from the DB seems to be unlike a session ID... any help would be greatly appreciated.

EDIT: Middleware... Although this is clearly working, the tokens do not match but when storing the session ID to the session and the DB, I use the same variable so how can they not be the same?!

//user not logged in, check session
                if (session()->has('at_token')) {
                    $token = session()->get('at_token');
                    if ($token == $booking->token) {
                        //user has the token, give them access
                        return $next($request);
                    }else{
                        Log::info("AT_TOKEN [$token] DOES NOT EQUAL THE BOOKING TOKEN [$booking->token]");
                    }
                }else{
                    Log::info('NO AT_TOKEN');
                }

Upvotes: 1

Views: 547

Answers (1)

Ujjwal Nepal
Ujjwal Nepal

Reputation: 546

The solution for your problem is here. https://laravel.com/docs/5.6/middleware#registering-middleware

also here https://laravel.com/docs/5.2/routing

The document states that by default the session is used inside middlewareGroups rather than middleware which is not assigned to the routes but rather assigned to web middleware. So the solution is to move the line

\Illuminate\Session\Middleware\StartSession::class,

to

protected $middleware = [
..........
\Illuminate\Session\Middleware\StartSession::class  
........
]

Now your session will persist.

Upvotes: 1

Related Questions