1

how to parse variable inside string?

here is a sample code that works:

$str =  "12345";
$str2 = "STR:{$str}";
$str3 = $str2;
echo $str2;
echo $str3;

but these won't work:

$otp = 12345;
$template = MessageTemplate::where('type',1)->first(); //db query
$message = $template->content; //content field, "OTP:{$otp}" 
echo $message;

this code prints OTP:{$otp} instead of OTP:12345

these is what we need:
$member = Member::where('id',$id)->with('position')->with('company')->first(); $otp = 12345; $template = MessageTemplate::where('type',1)->first(); //db query $message = $template->content; //content field, "OTP:{$otp}" $sms = Sms::Create(['mobile'=>$member->mobile,'message'=>$message]);

this code prints OTP:{$otp} instead of OTP:12345

Thanks for your responses. Actually what i need is to parse it before saving it to the database. the string "OTP:12345" should be written back to the databse. and also, variables are dynamic. It is a template to allow admin to customize the message, so the admin can add as many variable as he/she want. For ex: "{$member->title},{$member->firstName}, {$member->lastName}, in order to verify that you are {$mamber->position->name} of {$member->company->name}. enter code {$otp}".

so i can't use str_replace. and also our db supports json so admin can add a custom attribute to $member

2 Answers2

0

You can use mutators in your model like this

// MessageTemplate class
public function getContentAttribute($string)
{
    return 'OTP:' . $string;
}

// anywhere in controller
$message = $template->content; // will call content mutator
echo $message;
Ruben Danielyan
  • 728
  • 4
  • 19
0

The value of $template->content is just a string.

You can simply do a replace:

$message = str_replace('{$otp}', $otp, $template->content);
José Carlos PHP
  • 1,417
  • 1
  • 13
  • 20