如果 Laravel 路由文件中的条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29222216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:11:52  来源:igfitidea点击:

If Condition in Laravel Routes File

laravellaravel-5

提问by Sylar

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

有没有办法在 Laravel 5 的 routes.php 文件中使用 if 语句?我试过这个,但不起作用:

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.

我宁愿这种方式可行。谢谢。

回答by Andy

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

您需要最初使用 Route::group 而不是 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');
    }
});

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.

但是您可能想要做的是摆脱路由文件中的条件,并将其放置在通用索引方法中 - [email protected] 特别是如果 URL 无论如何要在两条路由之间保持相同。

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.

当然,这取决于你认为哪种方式更好。

回答by kamlesh.bar

you should use check()instead user()

你应该使用check()而不是user()

It's working in laravel 5. I have checked it

它在 Laravel 5 中工作。我已经检查过了

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

other things you did wrong is syntax for if/elseendif.

你做错的其他事情是if/elseendif 的语法。

回答by Ajay Kumar

You can use this

你可以用这个

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

In Laravel 5.3.* it works. it works for me so i think it should for you.

在 Laravel 5.3.* 中它可以工作。它对我有用,所以我认为它应该适合你。