Session does not save in first request in laravel 5.2 - session

My situation is weird.
I enclosed my routes in Route::group(['middleware' => ['web']], function () { /* Routes */ });
I save my session using
Session::put('customer_id', $customer->id);
But when I refresh my browser. The session is gone. Then I save it again then refresh and works fine. It does not works in first save.
I'm checking it using
if (Session::has('customer_id)) {
// Session saved.
} else {
// Session not saved.
}
I also tried middlewareGroup but doesn't work.

Does your $middlewareGroups array in app/Http/Kernel.php include the following line?
\Illuminate\Session\Middleware\StartSession::class
It would explain why the session isn't working.
The other thing to check is if the session is being overwritten elsewhere in your code. I.e. are you calling Session::put, anywhere else, and would $customer->id ever be null / false / 0?

Related

Laravel Delete a Cookie

When the user press the reset button on the filter, I want to delete the cookie that I previously created to save the user inputs and redirect to the same page "/search/influencers". I have searched all over stackoverflow and none of the listed ways to delete the cookie works. Please help!
/**
* resets the cookie that holds previous filter query
*/
public function resetFilter(Request $request){
if(Cookie::has('if_query_pref')) {
Cookie::queue(
Cookie::forget('if_query_pref')
);
}
return redirect()->route('influencerSearch'); //change the expiration time
}
Your code seems like fine, Please check that after removing cookie, it shouldn't reassign cookie.
I have used following code to remove cookie.
public function resetFilter(Request $request){
return redirect()->route('/influencerSearch')->withCookie(Cookie::forget('if_query_pref'));
}

Laravel 5: Sessions not working the way they should

On top of every controller and routes.php I used:
use Illuminate\Support\Facades\Session;
In routes.php I set the session using:
Session::put('key', 'value');
In a controller I want to call the session value of key using:
echo Session::get('key');
But once I set a new value to key in routes.php and call it in a controller, I still get the first value and not the new one. If I echo the the session using Session::all() in routes.php after setting it, I see the new value, but in a controller it flips back to the first value. I even tried using below in routes.php before setting the new value, but without success.
Session::forget('key');
Am I forgetting something here?
Using regular PHP $_SESSION my routes.php looks like this:
$slug = $_SERVER['REQUEST_URI'];
$slug = explode('/', $slug[0]);
if(in_array($slug[1], Language::all()->lists('iso'))) {
$_SESSION['language'] = $slug[1];
if(!$slug[2]) {
$_SESSION['slug'] = 'home';
Route::any('/{slug}', ['as' => 'pages.page', 'uses' => 'PagesController#page']);
} else {
if($slug[2] != 'dashboard' && $slug[2] != 'migrate' && $slug[2] != 'form-send') {
if (in_array($slug[2], ElementValue::where('element_field_id', 2)->lists('value_char')) && !isset($slug[3])) {
$_SESSION['slug'] = $slug[2];
Route::any('/{slug}', ['as' => 'pages.page', 'uses' => 'PagesController#page']);
} else {
$_SESSION['slug'] = 'home';
Route::any('/{slug}', ['as' => 'pages.page', 'uses' => 'PagesController#page']);
}
}
}
}
Where in routes.php are you setting the session value? It sounds like you're doing something like this:
Session::put('key', 'value');
Route::get('my-route', 'MyController#doSomething');
and then doing this:
class MyController {
public function doSomething()
{
Session::get('key');
}
}
Is that correct? If so, read on...
I'm no expert on the Laravel request lifecycle (for more, see the documentation), but it doesn't surprise me that this doesn't work. The way I think about it is this: the routes.php file is loaded and executed early in the life cycle - probably first - since it tells the application what code to execute next (ie. what do when a particular request is received). And when I say "early in the life cycle", I mean early - like before sessions are initialized. I believe that the Session::put call is simply being ignored, since at the time when you're setting the value, the session does not exist.
You may want expand your question with a little more detail about what you're trying to accomplish - there has got to be a better way to do it.
EDIT - in response to the comments below...
I am not saying you should touch the $_SESSION superglobal - that's a bad idea because I'm not even sure that Laravel uses the native PHP session facility and you have no guarantee that whatever you do will continue to work in the future.
It's not clear what you're trying to do, but to me this sounds like a value that does not belong in the session.
By placing the Session::put in the routes.php file, it sounds like you have some value that's important and should be set for every session and every request
If that's the case, and it's a static value, then it's not a session value, it's a configuration value.
If, instead, it's a dynamic value and/or it changes depending on which user is associated with a session, then you can set it in one of several places:
if you're using controller-based routing, you could set this in the controller constructor, although I wouldn't recommend it, because you will probably have to do it for several controllers, leading to code duplication
if you're using closures in your routes, set it there. E.g.
Route::get('some/route', function () {
Session::put('key', 'value');
// this works, because the closure isn't executed until after
// the application is initialized
});
you could also do it in middleware
or in a service provider (although I'm not certain that sessions would be available when the service providers are executed).
The best option is probably middleware - this would allow you to set (or calculate) the session value in one place in your code and also associate it with particular routes, if you don't need it for all routes.
Don't use $_SESSION in laravel. Uses the laravel Session class. See the following post How to access the globals $_SESSION and $_COOKIE from a laravel app?
Also, all your if logic should not be living in routes.php. You should add that to middleware to filter your routes.
Also, you are really making this hard for yourself. Laravel provides most of what you need in convenient helper classes e.g. Request::url(), Request::getHost(), Request::getLocale(). Have a read through the docs and get familiar with "The Laravel Way" it will be much easier and things will then work as you expect.
I moved the logic to the controller and now my routes are this simple:
Route::pattern('slug', '[a-zA-Z0-9\-_\/]+');
$slug = Request::path();
if(isset($slug)) {
Route::any('/{slug}', 'PagesController#index')->where('slug', '[a-zA-Z0-9\-_\/]+');
}
The session is stored in the PagesController and used further in the application. Thanks for your help guys.

fatfree sessions, different values in database and echo stmt

I have this in my beforeroute() of a controller
public function beforeroute()
{
new \DB\SQL\Session($this->db);
$mapper = new \DB\SQL\Mapper($this->db, 'users');
$auth = new \Auth($mapper, array(
'id' => 'username',
'pw' => 'password'
));
if (!$auth->login('validuser', '1234')) {
die('username or password wrong');
} else {
echo ($csrf = $this->db->exec('SELECT csrf FROM sessions')[0]['csrf']);
}
}
After I hit the page, I have different values for csrf in database and what's been echoed out on page. Why is that?
The csrf token is renewed on every request. You see different values on the page and in the database, because the value in the database was updated after your page has rendered.
To be more specific, the SQL Session handler replaces the default php session handler, and that's why the call to session_commit within the unload method https://github.com/bcosca/fatfree-core/blob/master/base.php#L1903 (is called when the framework shut down) will update your session database table with the new value.
To have a way to reuse that single csrf token for your purpose, just put it back into the session itself:
$s = new \DB\SQL\Session($f3->get('DB'));
// old value from last request
echo $f3->get('SESSION.csrf');
// remember current value for next request
$f3->set('SESSION.csrf',$s->csrf());
Maybe there`s an easier way, but I haven't figured it out yet.

Session value get deleted on page refresh in ci

I have a login function. When I login, the session gets saved. But when I refresh the page or redirect to another function, then the session (userdata) is shown blank. I have loaded the session library in autoload, but the userdata is deleted after every page refresh.
Here is my code.
public function index () {
$user = $this->input->post('user');
// after successful user checking
$this->session->set_userdata('user', $user);
// when I print session here,
print_r($this->session->all_userdata());
// session user gets print
}
But when I redirect to a function (suppose 'test'), then no any session is shown.
public function test() {
print_r($this->session->all_userdata());
die;
}
When you read the post value with $this->input->post('user'); and there isn't any post the function returns null and save this in the user value.
You have to check before setting.
if ($this->input->post('user')) {
$this->session->set_userdata('username', $this->input->post('user'));
}
I solved the problem. Actually, accidentally I had destroyed the session at the beginning of the code. So, my session was all destroyed. I removed the code and it's working fine.

Laravel FrozenNode Administrator run in maintenance mode

My question is: How can I leave the Frozennode administrator runs normaly on Laravel Maintenance Mode?
This is what I got in global.php
App::down(function()
{
return Response::view('maintenance', array(), 503);
});
Thanks!
I've dug in the core, there's no way you can do it. Laravel checks for a file named down in app/storage/meta folder, if it's there, Laravel won't even call the routes, it'll just show the error page.
This is isDownForMaintenance function from laravel:
public function isDownForMaintenance()
{
return file_exists($this['path.storage'].'/meta/down');
}
There's no configuration possible.
An alternative way to the laravelish "maintenance mode" is to set a new value in config/app.php, add:
'maintenance' => true,
Then add this to your before filter:
App::before(function($request)
{
if(
Config::get('app.maintenance') &&
Request::segment(1) != 'admin' // This will work for all admin routes
// Other exception URLs
)
return Response::make(View::make('hello'), 503);
});
And then just set :
'maintenance' => true,
To go back to normal mode
There is actually another way, more straightforward. As you can read in Laravel documentation, returning NULL from closure will make Laravel ignore particular request:
If the Closure passed to the down method returns NULL, maintenance mode will be ignored for that request.
So for routes beginning with admin, you can do something like this:
App::down(function()
{
// requests beginning with 'admin' will bypass 'down' mode
if(Request::is('admin*')) {
return null;
}
// all other routes: default 'down' response
return Response::view('maintenance', array(), 503);
});

Resources