Laravel Displaying Data

Display data that is passed to our Blade views by enclosing the variable in curly braces.

The following route is given below:

Route::get('greeting', function () {
return view('welcome', ['name' => 'rafia']);
});

We display the contents of the name variable like:

Hii, {{ $name }}
  • Blade {{ }} statements are sent through PHP`s htmlspecialchars function. It prevents XSS attacks.

We can put any PHP code where we wish to insert a Blade echo statement:

The current UNIX timestamp is {{ time( ) }}.

Displaying Unescaped Data

Blade {{ }} statements are automatically sent through PHP`s htmlspecialchars function to prevent XSS attacks.

If we need to escape our data, we have to  use the following syntax:

Hello, {!! $name !!}.

Rendering JSON

We pass an array to our view with the intention of rendering (providing) it as JSON to initialize a JavaScript variable.

For example:

 <script>
 var app = <?php echo json_encode($array); ?>;
 </script> 

However, instead of manually calling json_encode, we can use the @json Blade directive. The @json directive accepts the same arguments as PHP`s json_encode function do: 

 <script>
 var app = @json($array);
 var app = @json($array, JSON_PRETTY_PRINT);
 </script> 

The @json directive is also useful for seeding Vue components or data-* attributes:

<example-component :some-prop=’@json($array)’></example-component>
  • Using the @json in element attributes requires to be surrounded by single quotes.

HTML Entity Encoding

Blade ( and the Laravel e helper ) will double encode HTML entities. If we would like to disable double encoding, call the Blade::withoutDoubleEncoding() method from the boot method of our AppServiceProvider:

 <?php
 namespaceApp\Providers;
 useIlluminate\Support\Facades\Blade;
 useIlluminate\Support\ServiceProvider;
 classAppServiceProviderextendsServiceProvider
 {
 /**
      * Bootstrap any application services.
      *
      * @return void 
      */
 publicfunctionboot()
 {
 Blade::withoutDoubleEncoding();
 }
 } 

Blade & JavaScript Frameworks

JavaScript frameworks also use “curly” braces, which indicate that the given expression is displayed in the browser.

?We use @ symbol to inform the Blade, providing engine an expression that should remain untouched.

For example:

<h3> Laravel </h3>
 Hii, @{{ name }}.  

In the above example, @ (at the rate) symbol will be removed by the Blade.

However, {{ name }} expression will not be touched by the Blade engine.

The @verbatim Directive

If we are displaying JavaScript variables in a large portion of our template,

?we wrap the HTML in the @verbatim Directive. It is because we do not need to prefix each Blade echo statement within the @ symbol:

 @verbatim
 <div class="container">
         Hello,{{ name }}.
 </div>
 @endverbatim 

For example:

 @verbatim
 Name of javascript {{ name }}
 Type of application {{ type }}
 <!- - and few more like these -->
 @endverbatim
 </div>