What is a Laravel View & How to pass data from Controller to views?

A Laravel View makes up the frontend for Laravel applications. They write the HTML code how your frontpage in a Laravel app will look like in the blade language supported by Laravel. Views help keep the business and presentation layers separate. The Laravel controller handles the business and operations logic and passes variables to views.

A View blade will take in the variables passed by controller and show them in html format in any specified styling. Laravel uses a blade template engine to write html blocks of code. This engine is super fast and has the advantages listed below:

  • html escaping
  • easily understandable syntax
  • enables defining sections
  • extend or include sub views
  • allows use of if and loops statements

How to pass data from controller to view

A view blade displays data from controller values. Let us go through the example below to understand how controller passes data to a 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 the example above, we are rendering dashboard view along which we pass two variables called title and message. The Laravel view files are located a under resources/views directory.

A sample blade view file looks as shown below:

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

As seen above, we can simply call those variables passed from the Controller file with a $ sign and enclosed in curly braces wherever we want the variable value to show up in the blade view. So, in the example above, {{ $title }} comes up inside the <title> html tags.

How to Define a Layout

Working with views require defining the style and entire layout of the view blade file. The goal should be to keep it with minimal syntax and avoid duplicated code blocks. An example is as shown below.

<!-- 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>

How to Extend a Layout

A side wide layout can be re-used in other view blade files. It avoid code copy pasting or writing the same or similar code again and again. You can extend a layout in your child views to override default functions.

<!-- 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

How to use If Statements

You can also make use of if conditional statements in your Laravel blade view file using the @if directive, as shown below.

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

How to use Loops Statements

You can also make use of for and other loop statements in your Laravel blade view file using the @for, @foreach, and @forelse directives, as shown 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

How to use Loops with continue or break

Sometimes you may want to use a continue or break statement while doing looping. You may use the following syntax for it.

@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

What is the Loop Variable

While using loops, you have a special variable available that you may use for different purposes, for example:

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

At times you may want need to add some php code your blade view. You can use the following code block to execute php code in view blades.

@php
    //
@endphp

How to Include other views

You may use the @include blade directive to add other child views in a parent view file. Use include as shown 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

View Blades allow you to execute data based on specific conditions. For example show up a view blade part, only if you are authenticated. Use it with the syntax shown below.

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

JSON data

You can also create a JavaScript JSON variable in your view blade file with the following syntax below.

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

Other Uses

The code below shows use of some other blade directives like @isset, @auth, etc. That make using a view blade much simple and easier.

@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

Hope you like the tutorial. Stay tuned to more interesting Laravel tutorials!