Laravel Blade Templates Echoing PHP expressions


Any PHP expression within double curly braces {{ $variable }} will be echoed after being run through the e helper function. (So html special characters (<, >, ", ', &) are safely replaced for the corresponding html entities.) (The PHP expression must evaluate to string, otherwise an exception will be thrown.)

Echoing a variable

{{ $variable }}

Echoing an element in an array

{{ $array["key"] }}

Echoing an object property

{{ $object->property }}

Echoing the result of a function call

{{ strtolower($variable) }}

Checking for Existence

Normally, in PHP, to check if a variable is set and print it you would do

  • Before PHP 7
<?php echo isset($variable) ? $variable : 'Default'; ?>
  • After PHP 7 (using the "Null coalescing operator" )
<?php echo $variable ?? 'Default'; ?>

Blade operator or makes this easier:

{{ $variable or 'Default' }}

Raw echos

As mentioned, regular double braces syntax {{ }}, are filtered through PHP's htmlspecialchars function, for security (preventing malicious injection of HTML in the view). If you would like to bypass this behavior, for example if you're trying to output a block of HTML content resulting from a PHP expression, use the following syntax:

{!! $myHtmlString !!}

Note that it is considered a best practice to use the standard {{ }} syntax to escape your data, unless absolutely necessary. In addition, when echoing untrusted content (ie. content supplied by users of your site), you should avoid using the {!! !!} syntax.