Laravel same route, different controller

后端 未结 4 1267
执念已碎
执念已碎 2020-12-19 12:16

I would like to have general home page and a different homepage for logged-in users
I search a lot on google but I can\'t find what to put in my if statement

I t

相关标签:
4条回答
  • 2020-12-19 12:33

    ok after discussions on this platform and other forums, I come back with a compact solution

    Route::get('/', array('as'=>'home', 'uses'=> (Auth::check()) ? "usercontroller@home" : "homecontroller@index" ));
    
    0 讨论(0)
  • 2020-12-19 12:40
    // routes.php
    Route::get('/', 'homecontroller@index');
    
    
    
    // homecontroller.php
    class homecontroller extends BaseController
    {
        public function index()
        {
            if (!Auth:: check()) {
                return $this->indexForGuestUser();
            } else {
                return $this->indexForLoggedUser();
            }
        }
    
        private function indexForLoggedUser()
        {
            // do whatever you want
        }
    
        private function indexForGuestUser()
        {
            // do whatever you want
        }
    
    }
    
    0 讨论(0)
  • 2020-12-19 12:45

    You should try something like:

    Route::get('/', array('as'=>'home', function(){
        if (!Auth::check()) {
            Redirect::to('home/index'));
        }
        else{
            Redirect::to('user/index'));
        }
    }));
    

    So you are basically redirecting the user based on the Auth check instead of defining an additional route.

    Or use route filters

    Route::filter('authenticate', function()
    {
        if (!Auth::check())
        {
            return Redirect::to('home/index');
        }
    });
    
    Route::get('home', array('before' => 'authenticate', function()
    {
        Redirect::to('user/index');
    }));
    

    http://laravel.com/docs/routing#route-filters

    0 讨论(0)
  • 2020-12-19 12:52

    The most simple solution I can think of is:

    <?php
    
    $uses = 'HomeController@index';
    if( ! Auth::check())
    {
        $uses = 'HomeController@home';
    }
    
    Route::get('/', array(
         'as'=>'home'
        ,'uses'=> $uses
    ));
    

    Or you can just route the url / to method index() and do the Auth::check() in there.

    0 讨论(0)
提交回复
热议问题