skip to Main Content

I made a navbar using voyager’s menu builder. I’m trying to add localization functionality to my app but can’t figure out how to pass a {lang} parameter to this line of code:

@foreach ($items as $menu_item)
    <a href='{{ $menu_item->link() }}' class="nav-link">
@endforeach

Normally I would do this:

<a href='{{ route('shopIndex', App::getLocale()) }}' class="nav-link">Shop</a>

I tried doing this which didn’t work:

@foreach ($items as $menu_item)
    <a href='{{ route($menu_item->link(), App::getLocale()) }}' class="nav-link">
@endforeach

Any ideas?

2

Answers


  1. Chosen as BEST ANSWER

    SOLVED: running dd($menu_item) gave me these attributes:

      #attributes: array:13 [▼
    "id" => 18
    "menu_id" => 2
    "title" => "Shop"
    "url" => ""
    "target" => "_self"
    "icon_class" => null
    "color" => "#000000"
    "parent_id" => null
    "order" => 1
    "created_at" => "2023-02-12 07:31:09"
    "updated_at" => "2023-02-13 07:45:46"
    "route" => "shopIndex"
    "parameters" => null
    ]
    

    $menu_item->route gives the route name which I can put in a route helper and pass the parameters I want.

    Note: some links don't have a route name so you need to define a conditional in case of the links without a route name.

    <a href='{{ route($menu_item->route ? $menu_item->route : 'cartIndex', App::getLocale()) }}' class="nav-link">
    

  2. route() method is used only if you have named routes. If link() only returns a URL, you should not use it with the route() method.

    I see one that you want added by current language, like http://yoursite/en. Here are two methods you can follow to solve your problem:

    1. Create middleware and redirect according to current language. Use middleware by grouping your routes.
    2. Revise $menu_item->link() to give you the route name and use the route() method.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search