Laravel 5 route same urls login or not

502 views Asked by At

I am updating a site from Laravel 4 to 5. In L4 I had this set up:

if(Sentry::check()){ 
  Route::get('/', array('as' => 'school.home.index', 'uses' => 'school\AuthSchoolController@index'));
else{
 Route::get('/', 'school\SchoolController@index');
}

Note the same url but different controllers depending on login or not.

With L5 I cannot use the middleware tried this:

Route::get('/', 'SchoolController@index');

Route::group(['middleware' => 'auth'], function()
{   
    Route::get('/', array('as' => 'school.home.index', 'uses' => 'AuthSchoolController@index'));
});

But this just passes over the first and goes to the group, where it gets redirected to the login page and to the admin if logged in.

So I think I need an if/else equivalent in the route based on login but Auth::user() for doesn't seem to work:

if(Auth::check()){
  Route::get('/', array('as' => 'school.home.index', 'uses' => 'AuthSchoolController@index'));
}
else{
 Route::get('/', 'SchoolController@index');
}
2

There are 2 answers

6
Chukky Nze On

Try reordering the routes like so:

Route::group(['middleware' => 'auth'], function()
{   
    Route::get('/', array('as' => 'school.home.index', 'uses' =>     'AuthSchoolController@index'));
});

Route::get('/', 'SchoolController@index');
1
Serg S On
Route::get('/', function()
{
    if( Auth::check() ) {
        return app()->make('App\Http\Controllers\SchoolController')->callAction('index', []);
    } else {
        return app()->make('App\Http\Controllers\AuthSchoolController')->callAction('index', []);
    }    
});