1

I need a hierarchical structure for my language files in laravel. Imagine that I have following language file for /resources/lang/en/entity.php

<?php

return [

    'show' => 'Show Item',
    'view' => 'View Item',
    'edit' => 'Edit Item',
    'create' => 'Create a new Item',

];

Now I need a new file for post entity at /resources/lang/en/post.php but I don't want to copy all texts from entity.php file into the new file. I just need to change create message for the new entity. Something like following.

<?php

return [

    // Inherit the rest of texts from entity.php
    'create' => 'Create a new Blog Post',

];

Is there anyway to achieve this? Thank you all in advanced.

Hossein
  • 2,592
  • 4
  • 23
  • 39

3 Answers3

1

If you insist on to have something like inheritance behavior in your language files, as first solution that it comes in my mind is using to array_merge method:

// entity.php
return [
    'show' => 'Show Item',
    'view' => 'View Item',
    'edit' => 'Edit Item',
    'create' => 'Create a new Item',
];

// post.php
$terms = (include 'entity.php')

return array_merge($terms, [
    'create' => 'Create a new Blog Post',
];)

Have fun :)

Yaser Khahani
  • 685
  • 7
  • 15
0

You could create a new helper for that:

function translate($trans, $fallback) {
    return __($trans) === $trans ? __($fallback . '.' . explode('.', $trans)[1]) : __($trans);
}

And then use it like this:

translate('post.create', 'entity');
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
0

Instead of having lots of separate language files another approach would be to create a single file which groups labels for an element. For example, all of your button labels for the whole app could be stored in a file at /resources/lang/en/buttons.php You just need to be a bit more careful choosing labels. The contents of buttons.php could be

<?php

return [

    'show_item' => 'Show Item',
    'view_item' => 'View Item',
    'edit_item' => 'Edit Item',
    'create_new_item' => 'Create a new Item',
    'create_new_blog_post' => 'Create a new Blog Post',
    //add all labels here
];

Then if you need a button label anywhere on your site you can get it from the buttons.php file. For example, your show item button would be

<button type="button">{{ __('buttons.show_item') }}</button>
Dave Carruthers
  • 542
  • 1
  • 8
  • 29