You are in the right track of using middleware similar to localization. Here is the general gist:
- Create a SetUnit Middleware:
class SetUnit
{
public function handle(Request $request, Closure $next): Response
{
// if user has no unit, abort
if (!$request->user()->unit) {
abort(403, 'You are not allowed to access this resource.');
}
$requested_unit = $request->route('unit');
$users_unit = $request->user()->unit->slug; // name
URL::defaults(['unit' => $users_unit]); // auto-fills unit when using route()
// if current unit is not equal to user's unit, redirect to the user's unit dashboard
if ($requested_unit !== $users_unit) {
return redirect()
->route('unit.dashboard', ['unit' => $users_unit])
->with('error', 'Redirected to your unit.');
}
return $next($request);
}
}
- Register your middleware in
$middlewareAliases:
'set.unit' => \App\Http\Middleware\SetUnit::class,
- And the route something like this:
Route::prefix('{unit}')
->name('unit.')
->middleware(['auth', 'set.unit'])
->group(function () {
// All routes inside...
Route::get('/dashboard', function () {
dd(route('unit.dashboard'));
// you can see that {unit} fragment is automatically added.
})->name('dashboard');
});
Hope it helps.