Laravel Course

- Loops
- The $loop object
- Including Sub-Views

Blade template provides convenient shortcuts for common PHP control structures, such as conditional statements and loops.

if Statements

You may construct if statements using the @if, @elseif, @else, and @endif directives. These directives function identically to their PHP counterparts.
@if(count($records) === 1)
 I have one record.
@elseif(count($records) > 1)
 I have 1 records.
@else
 I don't have any records.
@endif

Check if a session exists

To check in template if a specified session exists, use: @if(session('SESSION_KEY')).
@if(session('SESSION_KEY'))
  do something with session key
@else
  session key dosen't exist
@endif
- Or: @if(Session::has('SESSION_KEY')).
@if(Session::has('SESSION_KEY'))
  do something with session key
@else
  session key dosen't exist
@endif

@unless and @endunless

@unless is the inverse of @if.
@unless ($condition) is the same as PHP: if(!$condition)
@unless(Auth::check())
 You are not signed in.
@endunless

@isset and @empty

In addition to the conditional directives, the @isset and @empty directives may be used as convenient shortcuts for their respective PHP functions:
@isset($records)
 $records is defined and is not null.
@endisset

@empty($records)
 $records is "empty".
@endempty

Loops

Blade provides simple directives for working with PHP's loop: @for , @foreach , and @while. They work the same in Blade as they do in PHP:
@for($i=0; $i<8; $i++)
 Current value: 0<br>
@endfor

@foreach($users as $user)
 <p>This is user {{ $user->id }}</p>
@endforeach

@while($item = array_pop($items))
{{ $item->fun() }}<br>
@endwhile

@forelse

@forelse is a @foreach that allows you to use a callback if the object you’re iterating over is empty.
@forelse($users as $user)
 <li>{{ $user->name }}</li>
@empty
 <p>No users</p>
@endforelse

@continue and @break

When using loops you may also skip the current iteration (with @continue) or end the loop (with @break):
@foreach($users as $user)
  @if($user->type == 1)
    @continue
  @endif

 <li>{{ $user->name }}</li>

  @if($user->nr == 5)
    @break
  @endif
@endforeach
- You may also include the condition directly in the $continue, and $break directives:
@foreach($users as $user)
  @continue($user->type == 1)

 <li>{{ $user->name }}</li>

  @break($user->nr == 5)
@endforeach

The $loop object

When looping, a $loop object will be available inside of your loop. This object provides a variety of useful properties:


- Example:
@foreach($users as $user)
  @if($loop->first)
   This is the first iteration.
  @endif

  @if($loop->last)
   This is the last iteration.
  @endif

 <p>This is user {{ $user->id }}</p>
@endforeach
- If you are in a nested loop, you may access the parent loop's $loop object via the $loop->parent property:
@foreach($users as $user)
  @foreach($user->posts as $post)
    @if($loop->parent->first)
     This is first iteration of the parent loop.
    @endif
  @endforeach
@endforeach

Including Sub-Views

Blade's @include directive allows you to include a Blade view from within another view.
All variables that are available to the parent view will be made available to the included view:
@include('sub_view')
You may also pass an array of extra data to the included view.
Also, it is indicated to use the @includeIf directive, to avoid errors if the specified view not exist.
@includeIf('sub_view', ['some'=>'data'])

@push and @stack

With @push() and @stack() you can define pieces of template that can be rendered somewhere else in that layout or into an included view.
- This can be particularly useful for specifying any JavaScript libraries required by your child views:
//define push-stacks in scripts.blade.php

@push('script1')
<script src="/scripts_1.js"></script>
@endpush

@push('script2')
<script>
//other script
</script>
@endpush
To render the contents of a @push, pass the name to the @stack() directive:
@include('scripts')

@stack('script1')
You can also use @include() and @stack() with dynamic name:
@includeIf('view_name'. $id)

@isset($js)
@stack('script'. $js)
@endisset

Practical example

1. Copy the following code and save it in a "resources/views/head.blade.php" file.
{{-- Define two js script push-stacks --}}
@push('script1')
<script>
alert('script_1');
</script>
@endpush

@push('script2')
<script>
alert('script_2');
</script>
@endpush

<!doctype html>
<html lang="{{app()->getLocale()}}">
<head>
<meta charset="utf-8">
<title>{{$title}}</title>
</head>
2. Copy the following code and save it in a "resources/views/page.blade.php" file, which includes the 'head' view, and uses a javascript @stack with a variable name in $js.
@include('head')

<body>
<div class="content">
{!! $content !!}
</div>

@isset($js)
@stack('script'. $js)
@endisset
</body>
</html>
I used {!! $content !!} statement to use HTML code in $content.

3. Now, we create a controller for pages data.
Add this code in a "app/Http/Controllers/TestBlade.php" file.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class TestBlade extends Controller {

  //receives the request object, and page ID; returns page view
  public function page(Request $request, $id=1){
    //define which javascript stak to use (set with @push in 'head' view)
    if($id ==1) $js =1;
    else if($id <4) $js =2;
    else $js ='';

    //set array with data to be passed to view() for template
    $data =[
      'title'=>'Title Page '. $id,
      'content'=>'<h3>Content of page'. $id .'</h3>',
      'js'=>$js
    ];

    return view('page', $data);
  }
}
4. Now, set up the route for "/page{id?}" to use the TestBlade.php controller.
Add the following code in the routes/web.php file:
//calls page() method of TestBlade controller
Route::get('/page{id?}', 'TestBlade@page')->where('id', '[0-9]*');
5. Visit the following URLs to see the output of the view, and the alert of the javascript script in the used stack according to $id.
//localhost:8000/page

//localhost:8000/page3

//localhost:8000/page9

- Documentation: Laravel - Blade Control Structures

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Blade Templates - Control Structures

Last accessed pages

  1. Mysql SELECT JOIN tables on two different Databases (4498)
  2. jQuery UI draggable - Drag elements (11448)
  3. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (142520)
  4. Using the Bone Tool (4253)
  5. Node.js Move and Copy Directory (20134)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (523)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (62)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)