【问题标题】:Laravel 4 routing to controller methodLaravel 4路由到控制器方法
【发布时间】:2014-05-21 02:38:40
【问题描述】:

我目前正在尝试如下路由:

  • 如果用户获取/account/
    • 如果会话有account_id,则用户已登录;显示他的帐户信息
    • 如果没有,用户没有登录;显示登录/创建表单
  • 如果用户发布/account/
    • 如果输入有create,用户想创建账号;创建它
    • 如果没有,用户想登录;找到他的帐户并再次访问/account/

我的路线是这样设置的:

Route::get('account', function() {
    if (Session::has('account_id'))
        return 'AccountsController@show';
    else
        return 'AccountsController@index';
});

Route::post('account', function() {
    if (Input::has('create')) {
        return 'AccountsController@create';
    else    
        return 'AccountsController@login';
)};

这有点像我对 Rails 的处理方式,但我不知道如何指向控制器方法。我只是得到返回的字符串作为结果。我在 Laravel 文档中没有找到它(我发现它真的很差,或者我搜索错了吗?)在任何其他网络教程中也没有。

【问题讨论】:

标签: php laravel laravel-4


【解决方案1】:

尝试以下方法:

Route::get('account', function() {
    if (Session::has('account_id')) {
        $action = 'show';
        return App::make('AccountsController')->$action();  
    }
    else {
        $action = 'index'; 
        return App::make('AccountsController')->$action();
    }
});

Route::post('account', function() {
    if (Input::has('create')) {
        $action = 'create';
        return App::make('AccountsController')->$action();
    }
    else {
        $action = 'login';
        return App::make('AccountsController')->$action();
    }
)};

【讨论】:

  • 使用过滤器实现这一点的最佳方法。我将尝试使用过滤器实现一个示例。
【解决方案2】:

因此,您希望将所有逻辑都放在控制器中。

你会想要做的

Route::get('account', 'AccountsController@someFunction'); 
Route::get('account', 'AccountsController@anotherFunction');

然后,在相应的控制器中,您会想要进行测试,然后执行,例如,

if (Session::has('account_id')){
    return Redirect::action('AccountsController@show');
}
else{
    return Redirect::action('AccountsController@index');
}

但是,请确保为每个操作定义一个路由,以便您的应用程序可以检测到一个 URL。
例如,如果你想拥有

 Redirect::action('AccountsController@show')

您需要像这样定义这个动作:

Route::get('/account/show', 'AccountsController@show')

【讨论】:

  • 好吧,因为用户不可能同时属于 2 个类别(如果他获取或发布,如果他是否登录等)我真的必须区分行动?我不想有更多的路由/页面,每个控制器方法只需/accounts/ 就足够了
  • 抱歉,不确定您要问什么。从技术上讲,您可以像以前一样将闭包放在 routes.php 文件中,但是返回重定向操作的最简洁方式是我上面展示的方式。
猜你喜欢
  • 2014-12-15
  • 2013-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
  • 2014-12-14
  • 2012-12-21
相关资源
最近更新 更多