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.
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.
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.
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.