Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Middleware overriding other middleware in Laravel

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?

like image 412
tmyie Avatar asked Nov 28 '25 13:11

tmyie


2 Answers

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' );
            });
        });
like image 79
Laravel User Avatar answered Nov 30 '25 02:11

Laravel User


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.

like image 34
Dany Aguilar Avatar answered Nov 30 '25 01:11

Dany Aguilar