Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Package cannot access session

Tags:

php

laravel

I am working on a laravel package for a cms system. I originally built it in laravel 5.1 and it was working fine but now I have tried using it on 5.2 and am getting issues with session data.

The issue I am facing is that for some reason session data is not accesible by the controllers inside my package.

The package is included using composer psr4.

Here is the boot method on my service provider loading my package routes:

// Include routes
if (!$this->app->routesAreCached()) {
    require __DIR__ . DIRECTORY_SEPARATOR . 'coreRoutes.php';
}

This is one of the routes I am testing:

Route::get('manager', [
    'as' => 'manager',
    'uses' => 'Cms\Controllers\CmsController@administrationPanel',
]);

This is the administrationPanel method inside the controller:

public function administrationPanel()
{
    var_dump(\Session::all());
    return view('Cms::front');
}

So with this var_dump I get an empty array. however if I var_dump inside one of the app controllers I get a populated array.

Does anyone know why the package controller cannot access the session data which a normal app controller can?

Am I loading things in the wrong order?

like image 368
AshNeedham Avatar asked Oct 29 '25 21:10

AshNeedham


1 Answers

Since Laravel 5.2 the StartSession middleware has been moved from the global $middleware list to the web middleware group in App\Http\Kernel.php. That means that if you need session access for your routes you can use that middleware group. So your route definition would look like this:

Route::get('manager', [
    'middleware' => 'web',
    'as' => 'manager',
    'uses' => 'Cms\Controllers\CmsController@administrationPanel',
]);

If you don't want/need all the other middleware added to that group (encrypted cookies, CSRF token verification, etc) you can setup a simple route middleware just for the seession like so:

protected $routeMiddleware = [
    ...
    'session' => \Illuminate\Session\Middleware\StartSession::class,
];

With this you can use session instead of web for your route middleware.

like image 140
Bogdan Avatar answered Nov 01 '25 10:11

Bogdan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!