Laravel同样的路线,不同的控制器

时间:2013-09-19 11:00:50

标签: php controller routing laravel laravel-4

我想有一般主页 和登录用户的不同主页
我在谷歌上搜索了很多但我无法找到我的if语句中的内容

我试过这样的事情:

Route::get('/', array('as'=>'home', function(){
    if (!Auth::check()) {
        Route::get('/', array('uses'=>'homecontroller@index'));
    }
    else{
        Route::get('/', array('uses'=>'usercontroller@home'));
    }
}));

我也尝试过类似的事情:

return Controller::call('homecontroller@index');

但似乎不适合laravel 4

我尝试了很多其他的事情,所以我认为这更像是一个误解问题

如果你有任何线索

感谢您的帮助

4 个答案:

答案 0 :(得分:9)

在这个平台和其他论坛上进行讨论之后,我回过头来看一个紧凑的解决方案

Route::get('/', array('as'=>'home', 'uses'=> (Auth::check()) ? "usercontroller@home" : "homecontroller@index" ));

答案 1 :(得分:5)

我能想到的最简单的解决方案是:

<?php

$uses = 'HomeController@index';
if( ! Auth::check())
{
    $uses = 'HomeController@home';
}

Route::get('/', array(
     'as'=>'home'
    ,'uses'=> $uses
));

或者您可以将url /路由到方法index()并在那里执行Auth :: check()。

答案 2 :(得分:1)

// routes.php
Route::get('/', 'homecontroller@index');



// homecontroller.php
class homecontroller extends BaseController
{
    public function index()
    {
        if (!Auth:: check()) {
            return $this->indexForGuestUser();
        } else {
            return $this->indexForLoggedUser();
        }
    }

    private function indexForLoggedUser()
    {
        // do whatever you want
    }

    private function indexForGuestUser()
    {
        // do whatever you want
    }

}

答案 3 :(得分:0)

你应该尝试类似的东西:

Route::get('/', array('as'=>'home', function(){
    if (!Auth::check()) {
        Redirect::to('home/index'));
    }
    else{
        Redirect::to('user/index'));
    }
}));

因此,您基本上是根据Auth检查重定向用户,而不是定义其他路径。

或使用路线过滤器

Route::filter('authenticate', function()
{
    if (!Auth::check())
    {
        return Redirect::to('home/index');
    }
});

Route::get('home', array('before' => 'authenticate', function()
{
    Redirect::to('user/index');
}));

http://laravel.com/docs/routing#route-filters

相关问题