If Condition in Laravel Routes File

2019-09-15 10:18发布

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.

3条回答
Rolldiameter
2楼-- · 2019-09-15 10:59

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.

查看更多
Melony?
3楼-- · 2019-09-15 11:00

you should use check() instead user()

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

 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/else endif.

查看更多
你好瞎i
4楼-- · 2019-09-15 11:13

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');
    }
});

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.

查看更多
登录 后发表回答