gramgram
gramgram

Reputation: 565

Conditional routing based on Middleware

I need to call different controller for the same url based on a middleware. The url has to be the same, so redirecting in the middleware is not an option. The code below is sample, controllers for dozens for routes are already finished, so checking the session value there is not an option either.

Tried to create two different middleware (has/hasnt the session value), but the latter route group overwrites the previous anyway. Any clue? Maybe a different approach needed?

route.php looks like this:

Route::group(array('namespace' => 'Admin', 'prefix' => 'admin', 'middleware' => 'auth'), function () {

    // set of default routes
    Route::get('/', array('as' => 'admin', 'uses' => 'FirstController@index'))->middleware('admin');
    Route::get('/profile', array('as' => 'profile', 'uses' => 'FirstController@profile'))->middleware('admin');

    Route::group(array('middleware' => 'sessionhassomething'), function () {
        // set of the same routes like above but overwritten if middleware validates    
        Route::get('/', array('as' => 'admin', 'uses' => 'SecondController@index'))->middleware('admin');
        Route::get('/profile', array('as' => 'profile', 'uses' => 'SecondController@profile'))->middleware('admin');
    });
});

SessionHasSomething middleware:

class sessionHasSomething {
    public function handle($request, Closure $next)
    {
        if(session()->has("something_i_need_to_be_set")) {
            return $next($request);
        }

        // return what if not set, or ...?
    }
}

Thanks in advance!

Upvotes: 0

Views: 1502

Answers (2)

thisiskelvin
thisiskelvin

Reputation: 4202

If you are only checking if session()->has('something'), it is possible to use route closures to add a condition within the route which needs to be dynamic.

Below is an example:

Route::get('/', function() {
    $controller = session()->has('something')) ? 'SecondController' : 'FirstController';
    app('app\Http\Controllers\' . $controller)->index();
});

->index() being the method within the controller class.

Upvotes: 1

Kapitan Teemo
Kapitan Teemo

Reputation: 2164

We almost have the same issue and here's what I did. (I didn't use middleware).

In my blade.php, I used @if, @else and @endif

<?php
   use App\Models\User;
   $check = User::all()->count();
?>
@if ($check == '0')
    // my html/php codes for admin
@else
    // my html/php codes for users
@endif

you can also do that in your controller, use if,else.

Upvotes: 0

Related Questions