[英]One route for different controller's actions
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).
我想在会话中用当前值切换控制器的动作,但不要改变路由(浏览器中的当前URL)。
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?!) 但是,返回的会话值始终为null(可能是值被缓存?!)
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 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 代码的第一个变体:总是打开一个动作'StravaController @ login',代码的第二个变种:打开空白页面
I woud like to expect an action 'StravaController@index' (is session values not empty) or an action 'StravaController@login' (if session values are empty) 我想期待一个动作'StravaController @ index'(会话值不为空)或动作'StravaController @ login'(如果会话值为空)
Send everything to one function: 将一切发送到一个功能:
Route::get('/', 'StravaController@handle');
and have that function call the login
/ index
functions accordingly: 并使该函数相应地调用
login
/ index
函数:
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. 另一种选择是将登录页面放在不同的路径上,如果“登录”数据不存在,让中间件重定向到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.