1 year ago

Write middleware to deny access to routes

Posted 1 year ago by pickab00

So in my laravel app I can menu items to each user. It works like tags. A pivot table handles belongsToMany relationship on both the tables (users table and menus table). Now the menu table has routes, name, icon etc. This acts as the menu items displayed on the left of the app. What I want to achieve is to be able to deny access to a route if the user does not have that menu item. So far what I have is this code in a middleware.

$auth_menu = User::with(['menus' => function($q){
            $q->whereIn('type', [1, 3])->orderBy('menu_index', 'asc');

And blade:

@foreach($auth_menu->menus as $menus)
        <a href="{{$menus->link}}">
            <i class="{{$menus->icon}}"></i>

So what that does is, it takes the authenticated user, and finds the user and get the related menu items to that user. Now how can I tell laravel to deny access to that route or abort to 404 if the user does not have a menu item. I want to do this because even though menu items are not displayed, they can still access from url

Please sign in or create an account to participate in this conversation.