Using the Blade service container I want to take a string with markers in it and compile it down so it can be added to the blade template, and further interpolated.
<This should do it:
// CustomBladeCompiler.php
use Symfony\Component\Debug\Exception\FatalThrowableError;
class CustomBladeCompiler
{
public static function render($string, $data)
{
$php = Blade::compileString($string);
$obLevel = ob_get_level();
ob_start();
extract($data, EXTR_SKIP);
try {
eval('?' . '>' . $php);
} catch (Exception $e) {
while (ob_get_level() > $obLevel) ob_end_clean();
throw $e;
} catch (Throwable $e) {
while (ob_get_level() > $obLevel) ob_end_clean();
throw new FatalThrowableError($e);
}
return ob_get_clean();
}
}
Usage:
$first_name = 'Joe';
$dbString = '<p>Welcome {{ $first_name }},</p>';
return CustomBladeCompiler::render($dbString, ['first_name' => $first_name]);
Thanks to @tobia on the Laracasts forums.