Jacob Kranz
Jacob Kranz

Reputation: 951

laravel 4 redirect to controller based off of conditions

Probably pretty simple, but I'm completely lost

Route::get('/', function()
{
    if(Auth::check())
        // send traffic to \Controllers\Home@index
    else
        // send traffic to \Controllers\Loggedout\Home@index
});

I've tried:

I have also named a two routes:

But it seems nothing is working.

I'm omitting the actual code to create the controller because it's quite standard and I know it works from Route::get('/', 'Controllers\Home@index') and it returns things properly.


Upvotes: 1

Views: 1103

Answers (4)

Gonzalo Cao
Gonzalo Cao

Reputation: 2424

My solution using just routes

Route::get('/', function()
{
    if (Auth::check())
        return Redirect::to('dashboard');
    else
        return View::make('index');

});

Upvotes: 0

mpj
mpj

Reputation: 5367

This should do the trick. First, in your routes:

// app/routes.php
Route::get('/', 'Controllers\Home@index');

Your controller:

// Controllers\Home class
class Home extends BaseController {

    public function __construct()
    {
        $this->beforeFilter('auth');
    }

    public function index()
    {

    }

}

And finally, your filters:

// app/filters.php
Route::filter('auth', function()
{
    if ( ! Auth::check()) {
        return Redirect::action('Controllers\Loggedout\Home@index');
    }
});

Upvotes: 1

ollieread
ollieread

Reputation: 6301

I just wrote a nice lengthy answer to this only to realise that I misunderstood your question.

To my knowledge, there's no simple way to achieve what you're doing in a single route declaration, instead, you'll want to use two.

Route::group(array('before' => 'auth'), function() {
    Route::get('/', array('as' => '\Controllers\Home@index'));
}

Route::group(array('before' => 'guest'), function() {
    Route::get('/', array('as' => '\Controllers\Loggedout\Home@index'));
}

Here we're using filters to group the individual calls so that they don't conflict. You shouldn't really be performing any extra logic within a route, but if you absolutely have to, then use a filter.

Upvotes: 1

mattems
mattems

Reputation: 78

Try returning the Redirect

 Route::get('/', function()
    {
        if(Auth::check())
            return Redirect::route('loggedin');
        else
            return Redirect::route('loggedout');
    });

Actually, this might just end up in a redirect loop as you are always returning back to /

Are you trying to show a different page depending on someones authentication status?

Upvotes: 0

Related Questions