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.

2
  • Why not create /resources/lang/en/buttons.php and share it for all your button labels?. Commented Dec 30, 2017 at 9:07
  • This is what I want. If there is anyway for this please let me know. Commented Dec 30, 2017 at 9:16

3 Answers 3

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 :)

Sign up to request clarification or add additional context in comments.

Comments

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');

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.