如果Laravel路由文件中的条件 [英] If Condition in Laravel Routes File

查看:47
本文介绍了如果Laravel路由文件中的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Laravel 5中的route.php文件中是否有if语句?我已经尝试过了,但是不起作用:

Is there a way to have if statements in the routes.php file in Laravel 5? I have tried this but does not work:

Route::get('/', function()
 {
   if ( Auth::user() )
     Route::get('/', 'PagesController@logged_in_index');
   else
     Route::get('/', 'PagesController@guest_index');
   endif
 });

我希望这种方式可以工作.谢谢.

I would prefer this way could work. Thanks.

推荐答案

您需要首先使用Route :: group而不是Route :: get-

You need to use Route::group initially instead of Route::get -

Route::group(['prefix' => '/'], function()
{
    if ( Auth::check() ) // use Auth::check instead of Auth::user
    {
        Route::get('/', 'PagesController@logged_in_index');
    } else{
        Route::get('/', 'PagesController@guest_index');
    }
});

但是您可能想要做的是摆脱路由文件中的条件,并将其放在通用索引方法-PagesController @ index中.尤其是如果两个路由之间的URL都保持不变.

But what you'll probably want to do is get rid of the condition in your routes file, and place it inside a generic index method - PagesController@index. Especially if the URL is to remain the same between both routes anyway.

public function index()
{
    return Auth::check()
        ? View::make('pages.logged-in-page')
        : View::make('pages.not-logged-in-page');
}

当然,这取决于您,您认为哪种方式更好.

Of course, it's up to you which way you think is better.

这篇关于如果Laravel路由文件中的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆