Reputation: 8502
I'm using Laravel Localization on my application (https://laravel.com/docs/5.0/localization)
I have the following strings:
'plan_month' => 'usd-plan-month',
'plan_yeary' => 'usd-plan-year',
Now, it's all good when I'm creating a subscription, I can access it with:
{{ trans('subscription.plan_month') }}
But.. when I want to retrieve the subscription, maybe to change the user plan, I would need to get the inverse, since stripe saves the plan ID on the database, and I need to get extra data about it..
My question is, is there a function in laravel or PHP (or most probably a hack) that I could feed the plan ID ('usd-plan-month' for example) and it would return the index name 'plan_month'?
Upvotes: 2
Views: 532
Reputation: 952
I don't think it is a good idea to get this from the lang file, as it is a data critical for the subscription. It should be saved as a constant or something, so you can make sure it won't change (and the lang file is prone to changes). Also, it would be an issue if there are two lang items that have the same value, but different key. You could get a wrong key, which would result with a bug in the subscription process.
In case you want to stick with this, there is a hack. You can get the lang array using
$lang = Lang::get('FILE_NAME');
It would be better if you have the translations nested in multiple arrays, so you don't need to iterate through the whole lang file (or have a separate lang file only for the subscription texts). If you want to access an array inside the lang file, you would have
$lang = Lang::get('FILE_NAME.ARR_KEY');
where FILE_NAME is the name of the file and ARR_KEY is the key of the array you want to access.
Then, you can either use array_flip to swap the array keys with their values (this would be better if you have to access multiple items), or use array_search to get the key for a given value (if you only have to look for one item).
I still think you should consider using constants for this purpose instead of a lang file. Language files are used for displaying content only and they shouldn't be mixed with the application logic.
Upvotes: 1