Reputation: 75
I want to use one route for one controller but different actions. I woud like to switch the action of controller by the current value in session, but don't change the route (current url in browser).
I tried this code:
$token = session('stravaAccessToken');
$athlete = session('stravaAthlete');
$stats = session('stravaStats');
if (empty($token) || empty($athlete) || empty($stats)) {
Route::get('/', 'StravaController@login');
} else {
Route::get('/', 'StravaController@index');
}
but, the session values returned always null (may be values are cached?!)
I woud like to use there code below, but there don't work as need... I have the session values as right as well, but, I don't understand, what do I need to return from callback function?
Route::get('/', function(){
$token = session('stravaAccessToken');
$athlete = session('stravaAthlete');
$stats = session('stravaStats');
if (empty($token) || empty($athlete) || empty($stats)) {
Route::get('/', 'StravaController@login');
} else {
Route::get('/', 'StravaController@index');
}
});
php 7.1, laravel 5.8
for first variant of code: always opened an action 'StravaController@login', for second variant of code: opened blank page
I woud like to expect an action 'StravaController@index' (is session values not empty) or an action 'StravaController@login' (if session values are empty)
Upvotes: 1
Views: 55
Reputation: 179994
Send everything to one function:
Route::get('/', 'StravaController@handle');
and have that function call the login
/index
functions accordingly:
public function handle() {
$token = session('stravaAccessToken');
$athlete = session('stravaAthlete');
$stats = session('stravaStats');
if (empty($token) || empty($athlete) || empty($stats)) {
return $this->login();
} else {
return $this->index();
}
}
An alternative option would be putting the login page on a different route, and having middleware redirect to it if the "logged in" data isn't present.
Upvotes: 3