2
votes

I’m currently building my first larval app.

I’ve got two user types: buyers and sellers. However, they both have access to the same routes, but they need to be served up different templates and data. For example, both would have access to /home, but see something completely different.

I know I can use an if statement within the route, but that’s getting messy. To try and fix this, I’ve made two separate middlewares using two different route groups. Each middleware checks the user for permission, and logs them out if they don't have it, like so:

        if ( Auth::user()->role !== 'buyer' ) {
            return redirect( 'login' );
        }

My goal:

  • If the user 'isBuyer', it only reads that middleware route group.
  • If the user 'isSeller', it only reads that middleware group.

I was hoping to use both in tandem:

// this will be triggered if they have the role 'buyer'
    Route::group(['middleware' => 'isBuyer'], function () {
        Route::get( '/', function (  ) {
            return view( '/home-seller' );
        });
    });

//this will be triggered if they have the role 'seller'

       Route::group(['middleware' => 'isSeller'], function () {
        Route::get( '/', function (  ) {
            return view( '/home-buyer' );
        });
    });

But it never reads the second group. It logs me out as a result of failing the auth test on the first group.

I assume this is because it's applying the middleware filter before it finishes reading the routes.php file. What's the best to deal with using the same routes for different user types?

3

3 Answers

2
votes

You can use something like this:-

    $middleware = '';
    if ( Auth::user()->role == 'buyer' ) {
                $middleware = 'isBuyer';
            }
    elseif(Auth::user()->role == 'seller') {
          $middleware = 'isSeller';
    }
else{
     return redirect( 'login' );
}

     Route::group(['middleware' => $middleware], function () {
            Route::get( '/', function (  ) {
                return view( '/home-seller' );
            });
        });
1
votes

How about use a single route and render from the controller (returning a view) depending the role using "if blocks" for each role. Can you try that.

1
votes

For this requirement, I think you should check the user role in your app controller/parent controller and depending on that role, redirect the user to their respective actions.