Laravel 5.2 session not persisting - php

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.

Related

How to use session data (auth) in the Laravel routes page

We have a large website with many pages. Almost all of them require the user to log in. Instead of specifying "Auth" on every single page, or on every single controller, I would like to set the routes based on if the user is logged in, like this:
// in web.php
if (Auth::isLoggedIn()) {
Route::get('/', function () { return view('pages/dashboard'); });
... lots more
}
The reason I can't do this is because Auth uses sessions, and sessions are not yet initialized in web.php, since it is done as middleware which is not run yet at this point.
I'm using Laravel 8, I believe.
Thanks.
you can group the route that need the user to be logged in, then use auth middleware
for the grouped routes:
Route::middleware(['auth'])->group(function () {
Route::get('/', function () {
//
});
Route::get('/', function () { return view('pages/dashboard'); });
});
Try using Laravel's Route middleware. Route middleware can be used to only allow authenticated users to access a given route.

Adding new simple route does not work in Laravel project. 404 not found. Is there any way to restart, reset or rebuild laravel project [duplicate]

This question already has an answer here:
Updates to Laravel route file have no effect
(1 answer)
Closed 1 year ago.
While being on learning curve with laravel, I have created the new project and installed jetstream on it, have experimented with preprocessor's configurations, and some other basic stuff. Right now when I have added the simplest it does not work:
Route::get('foo', function () {
return 'Hello World';
});
And all the previously added routes work fine.
Here is the whole web.php file:
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::get('/testcomp', function(){
return view('testcompmain');
});
Route::get('laravelProj3/login', function(){
return view('laravelProj3.auth.login');
});
Route::get('foo', function () {
return 'Hello World';
});
If any other files are helpful here, please let me know I will post them.
Is there any way to reset, or rebuild the project to force it to work again?
What if something like this happens while I am working on real project?
Can I somehow automatically copy all files that I added to newly build working application?
Is there any way except debugging to find where is the problem?
Update #1: Here is what I have found while debugging:
"Exception has occurred.
Symfony\Component\Routing\Exception\ResourceNotFoundException: No routes found for "/foo"."
Your route has been cached. It reduces all of your route registrations into a single method call within a cached file, improving the performance of route registration when registering hundreds of routes. If you want to clear the cached file, then simply hit :
php artisan route:clear
You can cache your route again by :
php artisan route:cache
For more info see the official documentation of Route Caching, Optimizing Views, Environment

Laravel routing strange behavior

I have a single domain/subdomain project. In order to see the event by slug, I made this route:
Route::prefix('events')->namespace('Content\Controller')->group(function () {
Route::get('/', 'EventController#getIndex')->name('event.index');
Route::get('{slug}', 'EventController#getView')->name('event.show');
Route::get('{slug}/edit', 'EventController#getEdit')->name('event.edit');
Route::post('load-more-ajax/{region?}', 'EventController#postLoadMoreAjax');
Route::any('sorted-ajax/{region?}', 'EventController#anySortedAjax');
Route::get('category/{category_slug}/{subcategory_slug?}', 'EventController#getCategory');
});
After my page didn't load correctly, I did a dump in the controller:
public function getView($slug)
{
return $slug;
}
To get to the route I am using this URL: https://example.com/events/slug-example.
The problem is that the route is being hit as I see the response when I change it, but I am not getting the slug, instead I am getting Region object back.
If I do this:
public function getView($region, $slug)
{
return $slug;
}
Then I get the slug back. But I have no idea how is this possible, and how could I do it (I came as another dev on the existing project).
I tried commenting out all the middleware and it is still the same. How can I even make something fill the method if I didn't explicitly say it?
EDIT
I noticed there is binding going on in routes file:
Route::bind('region', function ($value) {
...
});
Now if I dd($value) I get the variable back. How is this value filled? From where could it be forwarded?
Looking quickly it should work, but maybe you was verifying other url.
Make sure you put:
Route::get('{slug}', 'EventController#getView')->name('event.show');
Route::get('{slug}/edit', 'EventController#getEdit')->name('event.edit');
routes at the end of routes you showed.
EDIT
If you think that's not the case and you don't have your routes cached you should run:
php artisan route:list
to verify your routes.
EDIT2
After explaining by OPs in comment, domain used for accessing site is:
{region}.example.com
So having $region in controller as 1st parameter is correct behaviour because of route model binding and other route parameters will be 2nd, 3rd and so on.
Instead of
Route::prefix('events')->namespace('Content\Controller')->group(function () {
Route::get('/', 'EventController#getIndex')->name('event.index');
Route::get('{slug}', 'EventController#getView')->name('event.show');
Route::get('{slug}/edit', 'EventController#getEdit')->name('event.edit');
Route::post('load-more-ajax/{region?}', 'EventController#postLoadMoreAjax');
Route::any('sorted-ajax/{region?}', 'EventController#anySortedAjax');
Route::get('category/{category_slug}/{subcategory_slug?}', 'EventController#getCategory');
});
try
Route::prefix('events')->namespace('Content\Controller')->group(function () {
Route::get('/', 'EventController#getIndex')->name('event.index');
Route::post('load-more-ajax/{region?}', 'EventController#postLoadMoreAjax');
Route::any('sorted-ajax/{region?}', 'EventController#anySortedAjax');
Route::get('category/{category_slug}/{subcategory_slug?}', 'EventController#getCategory');
Route::get('{slug}', 'EventController#getView')->name('event.show');
Route::get('{slug}/edit', 'EventController#getEdit')->name('event.edit');
});

Laravel 5.2 token mismatch and middleware error

I'm using Laravel 5.2 and doing all authentication manually. So, although everything works, but I get a token mismatch error and the reason is that I'm not passing my routes through the web middleware in my routes file:
Route::group(['middleware'=>['web']],function (){
Route::get('/', function () {
return view('welcome');
})->name('home');
});
Route::social();
where Route::social(); is
public function social() {
$this->post('/signup',['uses'=>'UserController#postSignUp','as'=>'signup']);
$this->post('/signin',['uses'=>'UserController#postSignIn','as'=>'signin']);
$this->get('/dashboard',function() {
return view('dashboard');
})->middleware('auth');
}
But if I move Route::social(); to the web middleware group, it doesn't count errors and so return empty errors even if there are. How do I get around with it? I want both things!
I've the token field in my form using {!! Form::token() !!}
You are probably manually adding an $error array to your view, the web middleware will do the same thing so this will be overwritten. The web middleware group includes \Illuminate\View\Middleware\ShareErrorsFromSession which creates an error variable in the views with validation errors.
There are two ways to fix this. One is to only include the \App\Http\Middleware\VerifyCsrfToken middleware for this route. The other, wich I would prefer, is to add the route to the web middleware group, but use another name for your array with errors.

Laravel 5 Session not available for the second page

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

Categories