Session is not getting saved after page redirect in Laravel Application

2.4k Views Asked by At

I am redirecting the page after a successful login check and the session is created but the session is not available after page redirection.

My Login Controller:

$validated = $request->validate([
    'email' => 'required|email',
    'password' => 'required',
    'g-recaptcha-response' =>'required|captcha',
],
[
    "g-recaptcha-response.required" => "Captcha is required!",
]);

if(usernamd and password matches){
    session()->put("username",$username);
    return redirect()->route('home');   
}else{
    return Redirect::to("/login")->withFail('Wrong Passoword entered.');
}

if I print the session variables, they are visible and have proper values, but when it is redirected to the home page, the session variables are not set. session()->all() is showing empty array.

2

There are 2 best solutions below

1
On

I suggest you put the complete controller code. Sessions in Laravel only work with the "web" middleware defined in the App\Http\Kernel class. If you make the request from an API, you must use laravel/sanctum or manually start the sessions with the Session facade.

if (!Session::isStarted()) {
    Session::start();
}
0
On

In order to understand what you want to do, you need to provide more information. I think what you're trying to do is store a temporary value in the session for later use. Here is some code that can serve as a guide for that. As you probably know, there are many ways to write code, each one is written according to the need. However, you should simplify the code as much as possible. Try to follow Laravel conventions and best practices. Please read here.


<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class SomeController {
    public function store(Request $request)
    {
        $request->validate([
            'email'                => 'required|email',
            'password'             => 'required',
            'g-recaptcha-response' => 'required|captcha',
        ], [
            "g-recaptcha-response.required" => "Captcha is required!",
        ]);

        $user = User::whereEmail($request->email)->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'email' => [trans('auth.failed')],
            ]);
        }

        $request->session()->put(['login.username' => $user->username]);

        return to_route('home');
    }
}