Write middleware to deny access to routes

Posted 1 month 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');
        }])->findOrFail($auth->id);

And blade:

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

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.

Reply to

Use Markdown with GitHub-flavored code blocks.