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:
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?
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' );
});
});