duanfu6160 2019-07-17 13:49
浏览 63
已采纳

一种不同控制器动作的路径

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)

  • 写回答

1条回答 默认 最新

  • duanlu8613 2019-07-17 13:54
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答