php - Make multiple user types access the same Route using Laravel 9 middleware
I followed this site on how to create user types and restrict page access. Everything works as expected, but I wanted the admin to also have access to the users pages. The app has several hierarchical levels and I don't want to have to repeat the same Route several times, how can I do that?
Im using this: (short version)
routes/web.php
...
Route::middleware(['auth', 'user-access:usr'])->group(function () {
Route::get('/', function () {
return view('pages.activityHome');
});
});
Route::middleware(['auth', 'user-access:adm'])->group(function () {
Route::get('activity/{id}/edit', [App\Http\Controllers\activityController::class, 'editActivity'])->name('edit.activity');
});
Models/User.php
...
protected function type(): Attribute
{
return new Attribute(
get: fn ($value) => ["usr", "adm"][(int) $value],
);
}
Http/Middleware/UserAccess.php
...
public function handle(Request $request, Closure $next, $userType)
{
if(auth()->user()->type == $userType){
return $next($request);
}
// return response()->view('errors.check-permission');
}
Http/Kernel.php
...
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'user-access' => \App\Http\Middleware\UserAccess::class,
];
This way the adm doesn't have access to /, but he should, how can I do it?
I tried how to place more elements in the array and put several groups separated by a comma, but it doesn't work.
Like this: ['auth', 'user-access:usr', 'user-access:adm']
, ['auth', 'user-access:usr,adm']
Answer
Solution:
I tried a different way and it worked.
Http/Middleware/UserAccess.php
...
public function handle(Request $request, Closure $next, $userType)
{
if(in_array(auth()->user()->type, explode('.', $userType))){
return $next($request);
}
return response()->json(['You do not have permission to access for this page.']);
}
routes/web.php
...
Route::middleware(['auth', 'user-access:usr.adm'])->group(function () {
Route::get('/', function () {
return view('pages.activityHome');
});
});
I'm basically checking to see if any of the user types are in the array.
Source