l2t

Laravel Views

learn how laravel view works and available functions and filters

Laravel views allows you to write html code and help you separate your business layer with presentation layer. Laravel controller handles all your business logic and pass variables to views.

Views takes the variables passed by controller and present them nicely in html format. Laravel uses blade template engine to write html block. Blade template engine is fast and have following advantages:

  • easy to understand syntax
  • you can define sections
  • extend or include views
  • html escaping
  • loops and if statements

Passing data from controller to view

Let's first learn how to render a view and pass some data along with it. Following is a sample controller that renders a view file by passing some variables into laravel view file.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UserController extends Controller
{
    function example()
    {
        return view("dashboard", [
            "title" => "Home Page",
            "message" => "Hello World"
        ]);
    }
}

In above example, we are rendering dashboard view and we pass two variables called title and message. In laravel view files are located a under resources/views folder.

Let's have a look at sample blade view file:

<!-- resources/views/dashboard.blade.php -->
<html>
    <head>
        <title>{{ $title }}</title>
    </head>
    <body>
        <h1>{{ $message }}</h1>
    </body>
</html>

In above example, we used variables passed via controller and rendering some html along with it. Basically, blade views translate variables and renders html output on a browser.

Display data in blade view

Variables can be simply output using two curly braces and prefixed with $ sign. You can use filters to further apply any additional logic over the variable.

{{ $variable or 'Default Value' }}

Defining A Layout

When you work on a project you might want to define a master view that can be included in other layouts. Our goal is to use less syntax and get rid of duplicated code. You can define a main layout like this:

<!-- Stored in resources/views/layout.blade.php -->
<html>
    <head>
        <title>@yield('title')</title>

        @section('meta_tags')
            <meta property="og:type" content="website" />
        @show

        @section('styles')
            <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700">
        @show

        @section('scripts')
            <script src="{{ url('/js/bundle.min.js') }}"></script>
        @show
    </head>
    <body>
        @yield('content')
    </body>
</html>

Exending a layout

Once you have a site wide layout you can extend that layout in your child views to override default sections. Following is a sample child view that extends out layout.blade.php view file and override some of it's sections.

<!-- Stored in resources/views/child.blade.php -->

@extends('app')
@section('title', 'About Us')

@section('scripts')
    @parent
    <script src="{{ url('/js/analytics.js') }}"></script>
@show

@section('content')
    <p>This is my body content.</p>
@endsection

If Statements

You can also use if statements in your laravel blade view file just like this:

@if (count($posts) === 1)
    Single Post
@elseif (count($posts) > 1)
    I have multiple posts!
@else
    I don't have any post!
@endif

Loops

You can also use different types of loops in laravel blade view just like below:

@for ($i = 0; $i < 10; $i++)
    The current value is {{ $i }}
@endfor

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

@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse

@while (true)
    <p>I'm looping again and again.</p>
@endwhile

Loops with continue or break

Sometimes you may want to use continue or break statement while you are looping. You can use following syntax for that purpose.

@foreach ($posts as $post)

    @if ($post->type == 1)
        @continue
    @endif

    @if ($user->type == 5)
        @break
    @endif

    <li>{{ $post->title }}</li>

@endforeach

<!-- Alternatively -->
@foreach ($posts as $post)

    @continue($post->type == 1)
    @break($post->type == 5)

    <li>{{ $post->title }}</li>

@endforeach

The Loop Variable

When looping, you have a special variable available that you can use for different purpose like:

  • to know if we loop first or last item
  • to know current loop index etc..
@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

<!-- Parent Loop -->
@foreach ($users as $user)
    @foreach ($user->posts as $post)
        @if ($loop->parent->first)
            This is first iteration of the parent loop.
        @endif
    @endforeach
@endforeach

PHP Code

Sometime you might want to use php code withing your blade view. You can use following code block to execute php code:

@php
    //
@endphp

Include other views

In some cases to avoid duplicate code you can write a small view and then include this view in other file just like below:

<div>
    
    @include('errors')

    <!-- include a view that may or may not be present -->
    @includeIf('errors')
    
    <form>
        <!-- First argument is a view, second is an array, third is the variable name for current iteration -->
        @each('view.input, $inputs, 'input')
    </form>

</div>

Stacks

Blade allows you to push additional data to existing section using push code block as below:

@push('scripts')
    <script src="/laravel.js"></script>
@endpush

Unless

Sometime you want to execute piece of data when certain conditions are fulfilled:

@unless (Auth::check())
    You are not signed in.
@endunless

JSON data

Sometime you may want to create javascript json variable using following syntax:

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

Other Usage

There are some other useful syntax that you may like:

@isset($records)
    // $records is defined and is not null...
@endisset

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

@auth
    // The user is authenticated...
@endauth

@guest
    // The user is not authenticated...
@endguest

@switch($i)
    @case(1)
        First case...
        @break

    @case(2)
        Second case...
        @break

    @default
        Default case...
@endswitch

I hope you like this tutorial please spread and share your love. Thank you. To learn more in depth click the link below:

Laravel Blade