Laravel 5 Session not available for the second page - php

I am New in Laravel, and using Laravel 5
I am storing some values in Session like this
This is in a Controller with function say ABC
Session::put('check_in', $check_in);
Session::put('check_out', $check_out);
Session::put('no_of_rooms', $no_of_rooms);
Session::put('adult', $adult);
Session::put('child', $child);
return view('room');
I am getting the values of all these Sessions in rooms view, but now the problem is when I am going to some other link or on other page from this room view and using the Session as
echo Session::get('check_in')."<br>";
echo Session::get('check_out')."<br>";
echo Session::get('no_of_rooms')."<br><br>";
echo Session::get('adult')."<br>";
echo Session::get('child')."<br>";
I am not able to get any of these Sessions value.
I am using Sessions so it has to be on all the pages till the Session flashed or browser gets closed, but its not retrieving any of the Session values..
I have seen may topics like this on Stack Overflow, but I am not able to understand those answers, Please Explain me thoroughly and solve this Problem, I am stucked at this part from last 4 to 5 days clueless.......

If your using Laravel 5.*, then you should use 'web' middleware in all routes to use session.
This looks like this: in routes.php in app/http directory
Route::group(['middleware' => 'web'], function () {
Route::Auth();
Route::get('/', 'HomeController#index');
Route::get('/login', 'UserController#userLoginView');
Route::post('/login', 'UserController#userLogin');
}
You can use session in all those routes by declaring it under 'web' middleware.
I suggest you read more about 'web' middleware in Laravel 5.
Check this out:
My Laravel 5.2.10 Sessions wont persist
NOTE: As of Laravel 5.2.27 the web middleware is now in place by default, Try removing the Route::group and see if that helps. https://github.com/laravel/laravel/blob/v5.2.27/app/Providers/RouteServiceProvider.php#L56

Create a construction __construct() in your controllers that required the user to be connected:
public function __construct()
{
$this->middleware('auth');
}
and this automatically will check if the user is authenticated if not it will redirect them to login page

Related

Laravel application change session path dynamically

The laravel application url will be something like app.laravel.com\{clientName}. All the routes will be following the client_name, for example app.laravel.com\{clientName}\home, app.laravel.com\{clientName}\profile. Will load/ render the application depends on the clientName.
routes/web.php
Route::group(['prefix' => '{clientName}', 'middleware' => 'appclient'], function () {
Route::get('/', 'ClientController#index');
Route::post('login', 'Auth\LoginController#login');
Route::post('logout', 'Auth\LoginController#logout');
Route::get('home', 'HomeController#index');
});
In the appclient middleware
public function handle($request, Closure $next) {
$clientName = explode('/', $request->path())[0];
$client = Client::where('clientName', $clientName)->first();
if(!isset($client->id)) {
abort(404);
}
Config::set('session.path', "/$clientName");
return $next($request);
}
What I'm trying to achieve is set the session based on the clientName directory. When I login I'm getting TokenMismatchException.
First question
Can I store the session based on url with directory like app.laravel.com\{clientName} ?
Second Question
I saw there is a setting session.path, what above I tried is to use that approach. If that is possible, how can I fixed this issue? Is it a good idea to updating the session path in the middleware?
Appreciate any feed back or other approaches
UPDATE
Using Redis as session driver
In my further investigation the request session token every time generates new one
What I did is updated the session.path & session.cookie dynamically.
Config::set('session.path', "$clientName");
Config::set('session.cookie', $clientName.'_laravel_session');
This is currently working for me.

Laravel 5.2 user login redirects back to login for some reason

I have a Laravel 5.2 app and have used the artisan make:auth command. Everything was generated correctly, I changed my table name and managed to register. I then tried to login but I'm continually sent back to the login page. If I put incorrect credentials in on purpose, I get an error so I know my credentials are correct and that Laravel is communicating with the database.
I just have no idea why I keep getting back to the login page. Can anyone help? I have posted my routes below:
Route::auth();
Route::group(['middleware' => 'auth'], function () {
Route::post('entity/process', 'EntityController#process');
Route::get('entity/form/{subCategoryID}/{id?}', 'EntityController#viewForm');
Route::get('entity/delete/{id}', 'EntityController#delete');
Route::get('/viewList/{masterCategoryID}/{subCategoryID}', 'EntityController#viewList');
Route::get('/viewCategories', 'MasterCategoryController#viewAll');
Route::get('/', 'MasterCategoryController#viewAll');
});
Solution 1: Change this variable in App\Http\Controllers\Auth\AuthController
protected $redirectAfterLogout = '/login'
Solution 2: Write your own customLogout method in AuthController. Then override default logout route like this
Route::auth();
Route::get('logout', 'Auth\AuthController#customLogout');
After investigating further I found that the database ID field for my users table was null and was not set to auto increment. I changed it to 1 and enabled auto increment then everything worked as expected. Thanks for everyone's help.

Laravel 5.2 session not persisting

Lately I've been working on a project in Laravel 5.2 and now I'm having problems with sessions not persisting. I've read most of the questions already asked regarding this but everyone has the same answer that I have already tried - applying web middleware.
I've read that there was a new L5.2 update where the web middleware group is already applied by default. I checked my routes with php artisan route:list and I can see that every route has only 1 web middleware applied.
I'm creating session with $request->session()->put('key', 'value') but as soon as I comment that line the session is nowhere to be seen anymore.
Edit
I want to set the session inside a controller when I visit a news page, but I tried it on a simple test route as well. Route where I set this is news/{id} and I want to use it on the front page which is in /
I wish to store recently visited pages in session so I can then show it to the user on the front page.
Session config file I left untouched. So it's using file driver
Here is a tested routes to use for your projects
Please use a middleware instead of the function in the routes file
routes.php
// Only as a demo
// Use a middleware instead
function addToSession ($routeName) {
$visited = session()->get('visited', []);
array_push($visited, $routeName);
session()->put('visited', $visited);
}
Route::get('/', function () {
addToSession('/');
return view('welcome');
});
Route::get('/second', function () {
addToSession('/second');
return view('welcome');
});
Route::get('/third', function () {
addToSession('/third');
return view('welcome');
});
Route::get('/history', function() {
return session()->get('visited');
});
The /history route will return a JSON having the history.

How to set session in one method and get the session data in another method in laravel 5.2

This function will get the session value
public function getSession(){
$value =Session::get('email');
var_dump($value) ;
}
this function use to set the session values
public function setSession(){
Session::put('email', 'aaaaaaa.com');
$value=Session::get('email');
var_dump($value);
}
routes.php
Route::get('store','Product#setSession');
Route::get('display','Product#getSession');
when type display in url it's show NULL
As you use Laravel 5.2 probably you have to set your routes under the 'web' group to be able to use the session.
In fact, Laravel initializes the Session in the \Illuminate\Session\Middleware\StartSession::class middleware, that is grouped under the 'web' middleware group ( as you can see from the Kernel.php file )
So, to use the session, your routes should use that middlware:
Route::group(['middleware' => ['web']], function () {
Route::get('store','Product#setSession');
Route::get('display','Product#getSession');
});
Besides, i suggest you to close the request cycle properly, to be sure that the session will be set, for example:
public function setSession(){
Session::put('email', 'aaaaaaa.com');
$value=Session::get('email');
//this will end the request-lifecycle
return Response::json(['result' => 'ok']);
}
If you will install laravel 5.2 freshly, you can see in the route file a middleware ['web'] is added which comes under \Illuminate\Session\Middleware\StartSession::class , and if you will use the session under that group in route, session will work fine there or if you are using any other group, then you have to use that middleware.

laravel 5.2 authentication - Missing Links

I am new to laravel framework and trying to build up authentication for a website. There is something really strange thats happening and I am not able to figure out whats wrong.
I issue php artisan make:auth command and I could see the corresponding files getting generated under controllers and the resources/views. I am able to login and see the homepage (after login). I am able to logout as well and everything works smoothly so far.
now sometimes there seems to be a problem when I am away from the browser for sometime, and come back to the website, it starts acting wierd. the app loses the information about the current logged in user. If I go to the home page (the actual homepage of the website and not the page after the login), then the login page ("/login") does not show up. I have to manually logout (by typing "/logout" in the url) and then try the login url to see the login form.
this is my routes file:
Route::get("/", "PagesController#home")->name("home");
Route::get("/search/{query}","APIController#index")->name("search");
Route::get("/searchBook/{id}","APIController#searchBook")->name("searchBook");
Route::get("/stories","PagesController#stories")->name("stories");
Route::get("/user/{id}/deleteBooks/{book_id}","UserController#deleteBooks")->name('user.delete.books');
Route::get("/user/{id}/showBooks/{book_id}","UserController#showBooks")->name('user.show.books');
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::resource('user', 'UserController');
Route::get('/user/{user}/books',"UserController#books")->name('user.get.books');
Route::post("/user/{user}/createBooks","UserController#createBooks")->name('user.create.books');
Route::get('/home', 'PagesController#dashboard')->name("dashboard");
Route::post("/savemap","UserController#savemap")->name("savemap");
});
Also, It seems the app in itself is not really taking care of the authentication. I manually have to check the authentication (by Auth::check()) at lot of steps and it is painful. For example at many places I have to manually do
if (Auth::check()) {
// some code
}
else{
Auth::logout();
return redirect()->route('home'); //named route
}
This is an update : A route which was giving me issues was not placed under the web middleware in the routes.php file. So when I placed the concerned route under the web middleware, I was actually able to access all the Auth:: parameters and the current logged in user.
Does this mean that I have to place all my "logged-in" routes (available routes after logging in) inside the web middleware? and what about the /login, /logout routes... Should they be places any middleware?
Any route you need sessions (which Auth uses) needs to have the 'web' middleware group applied.
If you want to do auth checks you can use the 'auth' middleware which will do those checks for you.
Example:
Route::group(['middleware' => ['web', 'auth']], function() {
Route::get('mustbeauthed', 'SomeController#someMethod');
});
In this case going to the 'mustbeauthed' will redirect you away if you are not authenticated and let you pass through to it if you are authenticated.

Categories