karinegomes's avatar

List of available languages

Hey! I'm working on a multilingual project, and I was wondering if there's any function or helper package available on Laravel that retrieves all the languages defined on resources/lang, instead of manually adding a new language to an array everytime a new one is set up.

So, if we need to loop through all the languages available, everytime a new locale is added to resources/lang, it would be automatically picked up with no changes in the code.

Is there something available like getLocales() or any ideas on how to implement this? I'm currently using Laravel 5.2.

0 likes
8 replies
abbujan's avatar

Did you find an answer to this ?

1 like
eng.helewa's avatar

This code will do the job

$dir    = '../resources/lang';
$files2 = array_diff(scandir($dir), array('..', '.'));
print_r($files2);
1 like
impbob36's avatar

Confirmed works on PHP 5 or greater. Just remember to change the $dir directory to be relative to where-ever you are calling from.

1 like
noidentity's avatar

You can eliminate the relative $dir problem with the resource_path('lang') helper function.

1 like
yanzi's avatar

For newer Laravel versions (where the lang folder is not in the resources anymore but in the project's base folder) and with some more functionality:

/**
     * @param array array of required name replacements, eg. when you want to replace the 'en_BR' with just 'en', put ['en_BR' => 'en']
     * @return array return an array of available locales, eg. ['en', 'fr']
     */
    private function getAllLocales(array $replacements = []): array { 
             
        $locales = collect(array_diff(
            scandir(base_path('lang')), 
            ['..', '.'] // remove these strings from the result
        ))->filter(fn($item) => !str_contains($item, ".")) // removes all the files (these typically contain a dot in their name)
        ->map(fn($item) => $replacements[$item] ?? $item)->toArray(); // replaces all the given names (as key) in the $replacements argument with the specified new name (as value)

        return array_values($locales);
    }
raobilal4822's avatar

facing the same type of issue. i have a project in laravel livewire. when i change the language then the static data is changed but the data that is coming from the database is not converting into other language.

Please or to participate in this conversation.