Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

xoctopus's avatar

Laravel get the content of a translation file as an array

could you help me with the following question. I need to get the content of a translation file as an array regardless of whether it is a PHP file or a JSON file.

Suppose I have the following structure in my project:

laravel_project/resources/lang/
├── en
├── es
├── file1.php
├── file2.json
...

and I have the following method:

    public function example()
    {
        dd(__('file1', [], '/'));
    }

I get the following result:

array:2 [
  "failed" => "These credentials do not match our records."
  "throttle" => "Too many login attempts. Please try again in :seconds seconds."
]

Which is great since it is the content of the file1.php file, but I wonder how I can get the content of the file2.json file in the same way, because when I do the following:

    public function example()
    {
        dd(__('file2', [], '/'));
    }

I get the following result:

"file2"

The content of the file2.json file is the following:

{
    "A": "My string A",
    "B": "My string B"
}

I mean, it is not returning the content of the file file2.json. Is there an elegant way to achieve what I am trying to do? Basically what I am trying to do is return the content of a translation file regardless of whether it is a PHP file or a JSON file. Thank you very much in advance.

0 likes
3 replies
James_Bhatta's avatar

Maybe this work:

json_decode(file_get_contents('/path/to/your/file.json'));

xoctopus's avatar

@james_bhatta Yes, you are correct, using native PHP Functions I can get the result I need. My question was if using Laravel Translator class I could get that result, since as I describe above, when I try to get all the translations in a PHP file, it works fine, but I can't get it from JSON files. Is this normal?

James_Bhatta's avatar

" Translation files that use translation strings as keys are stored as JSON files in the resources/lang directory. For example, if your application has a Spanish translation, you should create a resources/lang/es.json file."

https://laravel.com/docs/8.x/localization#using-translation-strings-as-keys

The content of en.json file is following:

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ]
}

Return of dd(__('*'));

array:4 [▼
  "name" => "laravel/laravel"
  "type" => "project"
  "description" => "The Laravel Framework."
  "keywords" => array:2 [▼
    0 => "framework"
    1 => "laravel"
  ]
]
1 like

Please or to participate in this conversation.