t0berius's avatar

storing text with placeholders in database

For some actions I would like to store some messages including placeholders in my database. These messages are actions. What's the best way to retrieve them now and set the placeholder to some value? For example a message may look like:

'The ticket was closed by :username'

:username is a placeholder as you might suspect.

0 likes
5 replies
stevenobird's avatar

Well, you would go way more safe when you use resources/lang/ and use Lang::get('name') or the helper function trans('name').

When you go with strings that are not present in language files, you need to go with str_replace ( http://php.net/manual/en/function.str-replace.php ) and do it like that:

$model = Model::firstOrFail($id);
$username = Auth::user()->username;

$string = str_replace(':username', $username, $model->text_column);
d3xt3r's avatar

Have a small helper function that does

function compile_action_msg($message, $data) {
    foreach(array_keys($data) as $key){
            $message= str_replace(':'.$key,$data[$key],$message);
        }

    return $message;
}

@twaileit

Well, you would go way more safe when you use resources/lang/ and use Lang::get('name') or the helper function trans('name') .

Why ?

stevenobird's avatar

Getting strings from database is (a small) performance issue, when you can have easy localization over language systems like Laravel uses by default.

d3xt3r's avatar

These values rarely change so i have my cache warmed up by them. Anyway I was concerned with way more safe, and thought may be missing something significant.

stevenobird's avatar

I think "safe" is the wrong term, but according to localisation I would never go with database values (personal preference).

He could write an own implementation of localisation using the TranslatorInterface, which takes all strings from the database, but I think the file method is easier. And I don't see an important reason to store strings like these in a database.

Please or to participate in this conversation.