Skip to content

Instantly share code, notes, and snippets.

@lamualfa
Last active December 8, 2022 16:02
Show Gist options
  • Save lamualfa/03e4013e869c451c3a1377d918aa0759 to your computer and use it in GitHub Desktop.
Save lamualfa/03e4013e869c451c3a1377d918aa0759 to your computer and use it in GitHub Desktop.
Get translated Voyager Menu Items

Get translated Voyager Menu Items

According to this Voyager issue thedevdojo/voyager#3835, the author says there's no built-in function to translate the Voyager menu items. You need to write a custom function to solve it manually.

I've created a function to translate Voyager menu items for you. So you don't need to write it again.

Function to translate Voyager menu items

<?php

function translateMenuItems($menuItems, string $locale)
{
    $translatedItems = [];
    foreach ($menuItems as $item) {
        $translatedItem = $item->translate($locale);
        if (isset($item['children'])) {
            $translatedItem['children'] = translateMenuItems($item['children'], $locale);
        }

        array_push($translatedItems, $translatedItem);
    }

    return $translatedItems;
}

Example usage

<?php

use TCG\Voyager\Models\Menu;

$locale = 'en'; // https://voyager-docs.devdojo.com/core-concepts/multilanguage
$menuItems = Menu::display("menu-name", '_json'); // Get Voyager menu item with JSON form instead of HTML form
$translatedMenuItems = translateMenuItems($menuItems, $locale);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment