Home > Mobile >  laravel 8 - can i access a variable inside a constant inside my config
laravel 8 - can i access a variable inside a constant inside my config

Time:11-09

I have a series of constant strings that I am using for an application, placed inside a file called gameconstants inside my config directory

I'm using the config() function to get various messages, so the file looks similar to this

return [

'furiouspunches' => ' furiously punches ',
'kick' => ' kicks $loser in the junk ',

Is there a way for me to access that $loser variable? I'm using these constants to return strings for an app I'm building, so I end up concatenating this returned value, and the final output is something like

$winner . config('gameconstants.kick') . $loser

But the strings don't always play nice with the way this is, so I would like to access that variable so I can return different variations of that string.

I've tried

config('gameconstants.kick.$loser') but that doesn't work. Any thoughts?

Thanks in advance.

CodePudding user response:

You will want to use a string replacement, e.g.

return [

'furiouspunches' => ' furiously punches ',
'kick' => ' kicks {loser} in the junk ',

then

$string = $winner . str_replace('{loser}', $loser, config('gameconstants.kick'))

CodePudding user response:

You could use translation files instead of config files. Translation files also support parameter replacement.

Create a file at resources/lang/en/strings.php:

<?php

// resources/lang/en/strings.php

return [
    'furiouspunches' => ' furiously punches ',
    'kick' => ' kicks :loser in the junk ',
];

Then you access your string using the double underscore method (__()), and pass in the array of placeholder values:

$string = $winner . __('strings.kick', ['loser' => $loser]);

You can read up on the translation documentation and variable substitution here.


Depending on your use case, you may want to include both items in the strings. Maybe something like this:

<?php

// resources/lang/en/strings.php

return [
    'furiouspunches' => ':subject furiously punches :object',
    'kick' => ':subject kicks :object in the junk',
];

Then pass in both replacements:

$string = __('strings.kick', ['subject' => $winner, 'object' => $loser]);
  • Related