Home > Enterprise >  Laravel 7: How to pass variable inside string?
Laravel 7: How to pass variable inside string?

Time:08-03

I'm using a Laravel Package for sending SMS. Package Link: https://github.com/arif98741/laravelbdsms

sms_settings Table:

id ac_open ac_open_sms
1 1 Hello {$name}, Your Account has been created

My controller:

 $sms_settings = SmsSetting::where('id', 1)->first();
 $name = $request->name;
 $msg =  $sms_settings->ac_open_sms;
 $send= SMS::shoot($request->mobile, $msg);

Here I want to save the message body in database. While saving I want to pass a varibale $name. So that I can show the name anywhere in message body. While sending the message it shows client error. If I set the message body like this: $msg = "{$name}, \r\n Your account has been created"; it works.

How can I make it work?

CodePudding user response:

You can try str_replace to replace the {name} with what you get from request. I don't really understand the logic but here you go:

str_replace("{$name}",$name,$msg);

Also quick tip, instead of

 $sms_settings = SmsSetting::where('id', 1)->first();

You can try:

 $sms_settings = SmsSetting::findOrFail(1);

CodePudding user response:

You can replace the placeholder with:

$msg =  str_replace('{$name}', $name, $sms_settings->ac_open_sms);

or use translations with variables:

replace {$name} with :name and:

$msg = __($sms_settings->ac_open_sms, ['name' => $name]);

With the last option you can also translate the message in the future

CodePudding user response:

As far as I understand you want to pass user name instead of {$name}

so you can pass name before save message in database like this $msg = "$name, \r\n Your account has been created"; or $msg = $name . ", \r\n Your account has been created";

if you want to pass user name after select row from database or before shoot sms you can do this

$msg=str_replace("Jo","{$name}",$sms_settings->ac_open_sms);
  • Related