Laravel Blade Reference

Here are some of the Laravel Blade snippets that we use when we code our views- 

1. To output a variable on blade template:-


Laravel by default escapes the data before display:-

{{ '<script>alert("spam spam spam!")</script>'}}
will appear as plain text because it escapes.

However to output an un-escaped data on view, use below method:-

{!! '<script>alert("spam spam spam!")</script>' !!} will run this js alert on window.

Blade comments:-

{{-- Output the $name variable. --}}

Determining variable existence:-

{{ $school or 'Don Bosco' }}

Looping over an array:-

@foreach($mylist as $list)
@for ($i = 0; $i &lt; 10; $i++) 
    The current value is {{ $i }} 
@while (true)
   Iam looping forever.

If conditional:-

@if (condition)
@if (condition)
@if (condition)

Helper functions:-
To provide URL on views:-

 url('/articles', $articles->id)

Service Injection:-

@inject('metrics', 'App\Services\MetricsService')
Monthly Revenue: {{ $metrics-&gt;monthlyRevenue() }}.


To create a layout, first create a directory within resources/views called layouts


The @yield directive identifies the name of the section that should be embedded into the template.

Then open view template, if the layout file is master.blade.php-


The @extends directive tells Laravel which layout should be used


Defining Multiple Layout Sections:-
On layout file:-

<div class="container">
 <div class="col-md-9">@yield('content')</div>
  <div class="col-md-3">
   @section('advertisement')This is an advertisement!

@show directive means- close that section and yield it immediately else you need to explicitly define like below-


On view blade templates, you can reference these sections as well, like below

    Here goes the advt. contents.....

This will prepends the layout data appear in that section with view data appear in that section.
if we don’t add @parent then layout date appear in advertisement section will be eliminated and view section data will only appear.

Including View Partials:-


All variables that are available to the parent view will be made available to the included view

You can also pass an array of extra data to the included view like

   @include('', ['var'=>'data'])
   @foreach ($links as $link)
      @include('partials.row', array('link' => $link))

That’s all for now. Happy coding.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.