Skip to content
Advertisement

Blade – Print variable into variable

I am trying to print a variable into another variable in a blade template. I have a variable from database that contains “dynamic” data from another variable.

Example:

$foo = 'user';
$bar = 'Hello {{$foo}}, how are you?';

In blade I am doing this:

{!! $bar !!}

But the result is:

Hello {{$foo}}, how are you?

I tried with {{}} but the result is the same.

I can’t concatenate both variables. For example:

$foo = 'user';
$bar = 'Hello ' . $foo . ', how are you?';

It isn’t possible because I don’t have the control of the variables, they are filled dynamically from database.

Any idea/suggestion?

Thanks

Advertisement

Answer

Use eval function if the input is not direct from user,and remove {{...}} double curly bracket. you can used below code in .blade.php file

@php
    $foo = 'user';
    $bar = eval('return "Hello $foo, how are you?";');
    echo $bar;
@endphp

You will get output as

Hello user, how are you?
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement