Laravel session() issue

Problem: After storing a session using session() helper, other pages cannot retrieve data from session. The solution is remove “exit();” in the same function because session is saved very late.

  1. Don’t need to add session_start() manually.
  2. Don’t stop the process using “exit()” or “die()” after storing a session because session could be not saved yet.
  3. session won’t work in construct because middleware is not ready yet.
    https://stackoverflow.com/questions/39186222/laravel-5-3-auth-check-in-constructor-returning-false/39188299#39188299

Manipulations

$items = session('cart');
session()->forget('cart');

Child class:

class ProductC extends ParentC
{
    public function __construct(){
        //Important!!
        parent::__construct();
    }

    public function index(Request $req){
        //Will print value from ParentC::__construct
        dd($this->user);
    }
}

Parent Class:

class ParentC extends Controller
{
    protected $user = null;

    public function __construct(){
        $this->middleware(function ($request, $next) {
            $login_id = session('admin_id');
            if($login_id != false){
                $this->user = UserM::find($login_id);
            }

            return $next($request);
        });
    }
}

Reference: