Learning Management Platform for Written Tutorial Series.

Laravel 6 Blade Template

Laravel 6 Blade Template

In the MVC pattern, V stands for the view. Views are responsible for formatting and presenting information to the user in the web browser. The views will contain HTML, CSS, JavaScript etc to craft beautiful interfaces for the user. Blade is a view templating engine that Laravel uses to present information to the user. A template is like a framework that allows you to create HTML pages and inject data from data sources like the database with simplest. Template engines usually use pseudocode like language which designers can easily understand and use without bothering themselves with the backend programming.

Topics to be covered

  • Introduction to Blade Template
  • Passing Data to Views
  • Blade Directives
  • Blade If Control Structure
  • Blade For each Control Structure
  • Blade Template Inheritance
  • Blade Call PHP Function
  • Blade PHP Directive
  • Partial Views
  • Composer Views
  • Blade Creating Named Route Links

Introduction to Blade Template

As we stated in the above section, blade is a templating engine that is built into Laravel framework. In this section, we will create our first blade template. Blade templates end with .blade.php extension and they are stored in the directory /resources/views directory.

Let us now create a simple blade template that prints Hello World in the browser

Create a new file hello.blade.php in the directory /resources/views

Add the following code to our blade view

<p>hello world!</p>

HERE,

  • <p>hello world!</p> creates a HTML paragraph element with the value hello world! in-between the tags

Let's now create a controller that we will be using when working with blade

Run the following artian command to create the controller

php artisan make:controller BladeController

Modify the code for our new class to the following

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class BladeController extends Controller
{
    public function index(){
        return view('hello');
    }
}

HERE,

  • return view('hello'); calls the view helper method and we pass in hello as the argument. This will make laravel look for a view called hello.blade.php that is located in /resources/views directory. Notice how we did not provide the path or *.blade.php extension. Laravel handles that for us.

Our final step is declaring a route that will call the index method in BladeController

Open /routes/web.php and add the following command

Route::get('/blade', 'BladeController@index');

Let us now start the built-in server by running the following artisan command

php artisan serve

Load the following URL

http://localhost:8000/blade

You should be able to see the following results

hello world!

Congratulations, you just created your first blade view in Laravel and yes its that simple.

Passing Data to Views

In this section, we will modify our program and pass parameters to our blade view.

Let's start with the route. We will modify it and make it accept an optional parameter

Route::get('/blade/{name?}', 'BladeController@index');

Next we need to update the controller method like so

public function index($name = 'world'){
    $params = [
        'name' => $name,
    ];

    return view('hello')->with($params);
}

HERE,

  • $name = 'world' we modify our method to accept an optional parameter that is initialized to world this means the value world will be used if no parameter is supplied.
  • $params = [ 'name' => $name, ]; defines an associative array variable $params
  • return view('hello')->with($params); loads the view hello and passes in our array variable $params as the a data parameter to the view.

Let us now modify our template so that we can display the value of name

Open the blade template and modify it as follows

<p>hello {{$name}}!</p>

HERE,

  • <p>hello {{$name}}!</p> uses double open and closing curly brackets {{$name}} to print the value of $name the PHP equivalent is echo $name

You can now load the following URL into your browser

http://localhost:8000/blade/chichi

You should be able to the following results

hello chichi!

Blade Directives

Directives are special commands in blade that perform a specific task. For example, the extends directive is used to inherit a parent view within a child view. The if directive is used to begin the if control statement. The yield directive is used to output content etc.

As we work with the proceeding sections, we will see how to use blade directives. Blade directives start with the @ sign. For example, the complete syntax for extends directive is @extends.

Blade If Control Structure

Blade also allows us to work with control structures to control what is printed. For example, if a user is not logged in, we can display a login link but if the user is already logged in then we can displa a logout link in its place.

The if statement in blade has the following syntax

@if (condition is true)
do something
@endif

HERE,

  • @if (condition is true) marks the beginning of the if statement that evaluates a given condition. do something is executed if the condition is true.
  • @endif ends the if statement

Let's now modify our view as follows

<p>hello {{$name}}!</p>

@if ($login == true)
<p>welcome to the system dashboard</p>
@endif

HERE,

  • @if ($login == true) checks if the value of the variable $login is true. If it is true then the text Welcome to the system dashboard is displayed.

Modify the index method of the BladeController as follows

    $params = [
        'name' => $name,
        'login' => true,
    ];

    return view('hello')->with($params);

HERE,

  • 'login' => true, defines a parameter login that is set to true

Load the following URL in your browser

http://localhost:8000/blade/chichi

You should be able to get the following results

hello chichi!

welcome to the system dashboard

Laravel blade if else statement

In the above example, we only displayed conditional text when the user is logged in, what if we want to display a message that is specific to users who have not logged in. We can do that like so

<p>hello {{$name}}!</p>

@if ($login == true)
<p>welcome to the system dashboard</p>
@else
<p>you need to be logged in to see the admin dashboard</p>
@endif

HERE,

  • @if ($login == true) evaluates the condition
  • @else defines the code block that should be executed if the condition is false.
  • @endif ends the if statement

Set the value of the parameter login in the index method to false then load the following URL

http://localhost:8000/blade/chichi

You should be able to see the following results

hello chichi!

you need to be logged in to see the admin dashboard

Blade For each Control Structure

Laravel blade provides us with a foreach directive that we can use to loop through a collection of items. In the following example, we will loop through an array of numbers from 1 to 5 and print out the squares of the numbers.

Modify the index method as follows to include a new parameter called roots

    public function index($name = 'world'){
        $params = [
            'name' => $name,
            'login' => false,
            'roots' => [1,2,3,4,5],
        ];

        return view('hello')->with($params);
    }

HERE,

  • roots' => [1,2,3,4,5], defines an array variable roots that has numbers from 1 to 5

We will now modify our view to the following

<p>hello {{$name}}!</p>

@if ($login == true)
<p>welcome to the system dashboard</p>
@else
<p>you need to be logged in to see the admin dashboard</p>
@endif

<h4>the squares of the roots</h4>
@foreach($roots as $root)
<p>The square of {{$root}} is {{$root * $root}}
@endforeach

HERE,

  • @foreach($roots as $root) uses the foreach directive to loop through the items in the array $roots
  • <p>The square of {{$root}} is {{$root * $root}} prints the value of $root then multiplies the value by itself to ge the square.

Load the following URL in your browser

http://localhost:8000/blade/chichi

You should be able to see the following results

hello chichi!

you need to be logged in to see the admin dashboard

the squares of the roots
The square of 1 is 1

The square of 2 is 4

The square of 3 is 9

The square of 4 is 16

The square of 5 is 25

Blade Template Inheritance

Websites usually have elements that are common to all the pages. For example, the top navigation, sidebars, footer etc are usually standard on all pages. Template inheritance allows us to create a parent template that will have all the common features of the site. The child template will only contain information that is unique to it and inherit the rest from the parent class.

Create a new directory layouts inside /resources/views

Create the following blade template parent.blade.php in the directory /resources/views/layouts

Add the following code

<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Laravel 6 Blade View</title>
    </head>
    <body>
        <div>
            <a href="#">Home</a> | 
            <a href="#">About Us</a> |
            <a href="#">Services</a> |
            <a href="#">Products</a> |
            <a href="#">Contact Us</a>
            <hr>
        </div>
        @yield('content')
        <div>
            <hr>
            <p><strong>Copyright 2019 - The Watcher</strong></p>
        </div>
    </body>
</html> 

HERE,

  • <html>...</html> defines standard HTML content.
  • @yield('content') uses the blade directive yield to insert the contents of a section called content

Let's now create a child template that will inherit from the parent view parent

Add a new file child.blade.php in the directory /resources/views

Add the following content to the child template that you just created.

@extends('layouts.parent')

@section('content')
<div>
    <p>This is content belongs to the child view</p>
    <p>The rest of the items on the page have been defined in the parent view</p>
</div>
@endsection

HERE,

  • @extends('layouts.parent') the @extends directive is used to inherit from the parent template
  • @section('content') the @section directive is used to define a section that contains content. This is the section that will be inserted into the parent template using the @yield('section') directive.

Let's now add a new route that we will use to view the template

Open /routes/web.php

Add the following route

Route::get('/web', 'BladeController@page');

Lets now create the page method in BladeController class

Open /app/Http/Controllers/BladeController.php and add the following method

    public function page(){
        return view('child');
    }

Load the following URL into your web browser

http://localhost:8000/web

You should be able to get the following results

Laravel 6 Blade Template

Blade Execute PHP Function

We can also use the double curly brackets to call PHP built-in functions like date, number_format etc.

You can call PHP functions like so

<h4>calling php functions</h4>
<p>The date is {{date('D M, Y')}}</p>
<p>The price is {{number_format(3600,2)}}</p>

HERE,

  • {{date('D M, Y')}} calls the PHP date function
  • {{number_format(3600,2)}} uses the PHPnumber_format function to format the number 3600 into 3,600.00

Blade PHP Directive

The PHP directive is used to execute raw php code. This makes it easy to work with regular PHP code inside blade view. This should be used as last resort because blade comes with a number of built-in directives that you can use to get started as a beginner.

You can embed raw PHP into your views like so

@php
//php code goes here
@endphp

Let's work with a simple example that prints even numbers that are less than 10

<h4>printing even numbers that are less than 10</h4>
@php
for ($i = 0; $i < 10; $i++)
{
    if ($i % 2 == 0)
    {
        echo $i;
    }
}
@endphp

HERE,

  • @php starts the PHP blade directive. Inside the PHP directive, we have regular PHP code
  • @endphp ends the PHP directive

Partial Views

Partial views are views that perform a narrow specific task and can be embedded into any view using the @include directive. We can use partial views to promote view reusability. Suppose you have an email subscription form or a side menu, you can create a partial partial that you can embed into any view section that needs to display the data. This saves you the time of having duplicate code within your views

Let's now look at a practical example. We will create a partial view that contains a form that will allow the user to subscribe to a newsletter

Create a new directory partials in /resources/views

Create a new file newsletter.blade.php in the directory /resources/views/partials

Add the following HTML to the partial view

<form method="GET" action="#">
    First name:<br>
  <input type="text" name="firstname"><br>
  Email:<br>
  <input type="email" name="email"><br><br>
  <input type="submit" value="Subscribe">
</form>

We will now modify the child view so that it can load the the newsletter partial view

Modify the code of /resources/views/child.blade.php to the following

@extends('layouts.parent')

@section('content')
<div>
    <p>This content belongs to the child view</p>
    <p>The header and footer on the page belong to the parent view</p>
</div>
@include('partials.newsletter')
@endsection

HERE.

  • @include('partials.newsletter') uses the @include directive to load the partial view newsletter

Load the following URL into your browser

http://localhost:8000/web

You should be able to get the following results

Laravel Blade Partial View

As you can see from the above results, we can reuse the newsletter form in any view that we want by using the @include directive.

Composer Views

Composer views allow us to define a callback function that is executed when a named view is loaded. Let's explain this with the aid of an example. Suppose we want to display the number of subscribes for our newsletter form above. We can retrieve the data from the database and pass it as a parameter. While this may work, it is not the optimal solution because we will have to pass data that we may not use if the newsletter form.

Composers can allow us to define a function that will only be executed when the newsletter view is loaded. The function once executed will pass data to the view that we can display.

Create a new directory ViewComposers in the directory /app

Add a new file NewsletterComposer in the directory /app/ViewComposers

Add the following code to NewsletterComposer

<?php

namespace App\ViewComposers;

use Illuminate\View\View;

class NewsletterComposer {

    public $subscribers = [];

    /**
     * Create a new newsletter composer.
     *
     * @return void
     */
    public function __construct() {
        $data = ['count' => 12]; //This can be retrieved from the database
        $this->subscribers[] = $data; 
    }

    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view) {
        $view->with('subscribers', end($this->subscribers));
    }
}

HERE,

  • namespace App\ViewComposers; defines the composer namespace
  • use Illuminate\View\View; imports the View object
  • class NewsletterComposer {...} defines a class NewsletterComposer
  • public $subscribers = []; defines a public array variable $subscribers that will be passed to newsletter view when it is loaded.
  • public function __construct() {...} defines a class constructor that actually populates the array variable that is passed to the view.$data = ['count' => 12]; defines an array variable with one element with the name of count that is assigned the value of 12. In normal circumstances this should be retrieved from the database. $this->subscribers[] = $data; assigns our $data array to the class variable $subscribers
  • public function compose(View $view) {...} defines a function compose that binds the data to the view. $view->with('subscribers', end($this->subscribers)); passed a parameter subscribers that has the value of the variable $this->subscribers.

We will now need to create a Composer Service Provider

Run the following command in the terminal

 php artisan make:provider ComposerServiceProvider

HERE,

  • The above command creates a service provider ComposerServiceProvider.php in the directory /app/Providers

Open ComposerServiceProvider.php and modify the code as follows

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        view()->composer(
			['partials.newsletter'],
			'App\ViewComposers\NewsletterComposer'
        );
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

HERE,

  • public function register(){...} the register method binds the composer App\ViewComposers\NewsletterComposer to the view partials.newsletter

Before we can use our composer service provider, we need to register it like so

Open /config/app.php

Add the following line to array variable providers under the section of Application Service Providers...

App\Providers\ComposerServiceProvider::class,

Finally, we need to update the newsletter view so that it can display the total number of subscribers like so

<h4>Join {{$subscribers['count']}} subscribers</h4>
<form method="GET" action="#">
    First name:<br>
  <input type="text" name="firstname"><br>
  Email:<br>
  <input type="email" name="email"><br><br>
  <input type="submit" value="Subscribe">
</form>

HERE,

  • <h4>Join {{$subscribers['count']}} subscribers</h4> prints the value of $subscribers['count'] in the header. This parameter is automatically provided for us when newsletter is loaded. We don't have to pass in it from the controller.

We are now good to go

Load the following URL into your web browser

http://localhost:8000/web

You should be able to see the following results

Laravel 6 View Composer

As you can see from the above results, our view newsletter knows that we have 12 subscribers without been informed by the controller. The composer does it for us.

Blade Creating Named Route Links

In this section, we will look at how you can create URL links for named routes. A named route is simply a link that has a name. Instead of creating links like /about-us, Laravel allows us to use the route name like about.us

In the above sections, we defined two named routes home and pages. Let's now update the parent view so that we can display named routes.

Open the view parent.blade.php which is located in /resources/views/layouts directory

Update the code to the following

<!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Laravel 6 Blade View</title>
    </head>
    <body>
        <div>
            <a href="{{route('home')}}">Home</a> | 
            <a href="{{route('pages',['name' => 'chichi'])}}">Say hello</a> |
            <a href="#">Services</a> |
            <a href="#">Products</a> |
            <a href="#">Contact Us</a>
            <hr>
        </div>
        @yield('content')
        <div>
            <hr>
            <p><strong>Copyright 2019 - The Watcher</strong></p>
        </div>
    </body>
</html> 

HERE,

  • <a href="{{route('home')}}">Home</a> uses the route helper methods that accepts home as an argument. The argument is the name of the route that we want to link to.
  • <a href="{{route('pages',['name' => 'chichi'])}}">Say hello</a> creates a link for a named route pages that accepts a parameter of name. Route parameters are passed in via an array like so ['name' => 'chichi']

Summary

Laravel blade is an elegant easy to use templating engine that uses pseudocode to provide programming logic. Blade files are identified using the *.blade.php extension. Blade uses directives which are special commands that perform specific tasks. The @php directive is used to execute regular PHP code inside blade. Blade has support for control structures like if, switch, foreach etc. View composers allow us to execute special functions when a bound view is loaded.

What next?

If you enjoyed this lesson then show us your appreciation by creating a free accounts on our site. As always we appreciate your comments down below.


...