0

I am trying to have the same route homepage / but different controllers for auth and guest users but i am unable to do this. I have searched and tried all the results on google, stackoverflow etc, none have worked. I am guessing it is because of the version i am using Laravel Framework 7.15

 $uses = 'BlogController@index';
 if (!is_null(auth()->user())) {
     $uses = 'HomeController@index';

 }
 Route::get('/', $uses);

BlogController is for guest and HomeController is for authenticated users. So when i run the code for authenticated users it shows only shows the Blog(guest) homepage and not users HomeController page. Thanks for your help in advance.

Obinna Iloeje
  • 45
  • 1
  • 7

1 Answers1

2

You can try this.

Route::get('/', (function() {
    return auth()->user()
        ? app()->make(\App\Http\Controllers\HomeController::class)->index()
        : app()->make(\App\Http\Controllers\BlogController::class)->index();
}));
bangnokia
  • 259
  • 2
  • 9
  • Thanks but it didn't work. Error message is = `Action App\Http\Controllers\HomeController@index not defined.` – Obinna Iloeje Jun 19 '20 at 10:15
  • do you have index method in HomeController ? – Enver Arslan Jun 19 '20 at 10:19
  • Yes I do. It works with a straight up `Route::get('/', 'HomeController@index');` – Obinna Iloeje Jun 19 '20 at 10:22
  • sr, just updated my answer. redirect route action only works when you already have that action. So now we should make controller class and call the index function, but i think there will be another fluent way to do that. Will update the better answer when i found it – bangnokia Jun 19 '20 at 10:36
  • but i suggest you should try this solution, handle view in the controller is better: https://stackoverflow.com/questions/37618735/laravel-routes-same-route-different-controllers – bangnokia Jun 19 '20 at 11:31
  • Thanks the updated answer works perfectly now. I tried the answers to the recommended question before posting mine on here, and it didn't work. But yours worked! – Obinna Iloeje Jun 19 '20 at 11:50
  • @bangnokia Hey I am trying to add middleware `verified` to the route but I don't know where to add it. Can you help me on this one? – Obinna Iloeje Jul 01 '20 at 16:07
  • Apparently the route is bypassing my `$this->middleware(['auth', 'verified']` instance in my construct function in the `HomeController` – Obinna Iloeje Jul 01 '20 at 16:10
  • @bangnokia So I figured I have to add it to the route, – Obinna Iloeje Jul 01 '20 at 16:11
  • @ObinnaIloeje append your middleware to the end like this `Route::get('/',...)->middleware('auth', 'verify');` – bangnokia Jul 02 '20 at 15:32
  • @bangnokia You don't understand, I am asking how to append `middleware` to the route you gave me. If I append it the regular way as you stated, it will not show the `guest` index page... – Obinna Iloeje Jul 03 '20 at 12:08