What is view composer? When and how to use it?

corona image

Coronavirus Impact on eCommerce Industry!

View Composers:

View Composers are callback or a class method that gets executed when a view is rendered. That means when Laravel loads a *.blade.php file to serve to the browser to display contents it executes View Composers.

When to Use:

Suppose we have some data, we will be needing on multiple views or on any layout file that gets loaded into multiple views. Writing the logic or executing a query inside the blade is bad practice. Or passing the data from multiple controller functions is not a good idea either. That’s exactly when view composers comes into play. Let me give you some example and procedure on how to use view composers to bind data to multiple views using a single logic location.

Procedure to use View Composers:

Suppose we have an e-commerce application that has many categories stored in DB. And we will need the categories list in every view that is being rendered.

We can send the categories to home page like this

public function index() {     $categories = Category::all();     return view('welcome', compact('categories')); } 

Rendered Data

If we need the category list on /home page, we’ll have to do the same query for the same listing in different function. Now imagine what if we need the data on many pages. Doing that same query over and over again makes it hard to maintain code base. But using View Composers, we can pass the data to multiple view files from one logic block. Let me show you how we can do that.  

First lets create a ViewComposer Service provider by running command
php artisan make:provider ComposerServiceProvider

The newly created ComposerServiceProvider will look like this.

Now let’s add the ComposerServiceProvider class to config/app.php providers array so that Laravel can recognise it.

On the next step lets create a View Composer CategoryComposer class inside App\Http\ViewComposers folder.

Modify the boot method in the new Provider by adding a composer method that extends view().

public function boot()
{
view()->composer(
'app',
'App\Http\ViewComposers\CategoryComposer'
);
}

Laravel will execute a CategoryComposer@compose method every time app.blade.php is rendered. This means that every time the view is loaded , we will be ready to show the categories in home.blade.php & welcome.blade.php with the categories list from our view composer.

Next, we’ll pass the categories list from our view composer to our views from the compose method.

public function compose(View $view)
{
    $categories = Category::all();
    $view->with(['categories' => $categories]);
}

Now we can access the categories array on both view files without needing to send data from multiple controller functions.

** Controller **
public function index()
{

    return view('home');
}

public function welcome()
{

    return view('welcome');
}

Accessing the categories array on welcome.blade.php

@extends('layouts.app')
@section('content')
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Dashboard</div>

                    <div class="card-body">
                       <ul class="list-group">
                           @foreach($categories as $category)
                           <li class="list-group-item">{{$category>title }}</li>
                               @endforeach
                       </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @endsection

Note: It is possible to create a view composer that is executed when all views are rendered by replacing the view name with an asterisk wildcard

view()->composer('*', function (View $view) {
    //Logic block
});

That’s all for today. See you one the next one.

Share this post

In the previous blog ( Things you need to know about Laravel in 2019) I talked about Laravel and its origin, current and future position in the Web Application/Software development field. This is going to be a small series on Laravel where I will start from the basics and in the end you will have a ready to deploy small CRUD application. As you are following the tutorial I expect you have a basic understanding of Object-Oriented Programming PHP & MySQL. So in this tutorial series, we will follow the official laravel documentation. The documentation will help guide you through if you face any difficulties. So let’s begin.

In this tutorial, we’ll learn the basics of Laravel application installation and running your first Laravel starter application.

Installation:

To start building your first Laravel application you’ll need to install some dependencies first. As the Laravel framework has few requirements So Homestead comes with all the requirements you need to work on your Laravel application. Homestead is an official virtual machine for Laravel. In the next tutorial of this series, I’ll discuss everything you need to know about it. So, for now, will just stick to the most simple one. I am using Ubuntu but You may use any OS you prefer. Because Everything is almost the same. So there’s no need to panic.

As we are not using Homestead for this part of the tutorial, So you need to make sure you have PHP and its extensions installed on your local computer. Therefore I am assuming you have a basic understanding of PHP you should have PHP and its extensions installed on your system.

Now you need to install Composer on your machine. So to install composer just open up your terminal, type in the following command and press enter.

Installing composer:


php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

php -r "if (hash_file('sha384', 'composer-setup.php') === '48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd0615698a5cbe587c3f0fe57a54d8f5') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

php composer-setup.php

php -r "unlink('composer-setup.php');"

After installing composer run the command below to install composer for Laravel globally on your system.

Run composer to check whether the composer is installed properly or not.

Composer Installation check & Composer commands


composer global require laravel/installer

Once you are done installing composer you are ready to create your first Laravel starter application.

To create your first Laravel application run composer create-project --prefer-dist laravel/laravel crud. On this command “crud” is the name of the application. You can type any name you prefer instead of crud. As I prefer to create all my applications inside a folder to keep everything organized, So For me it’s inside the Documents/projects folder. So I will CD into the folder and run the command to create the application.

Creating a new project from composer command

After successfully running the command composer will start setting up a fresh Laravel application in your Documents/projects folder. And it will look like this.

Project files & folders

The next thing we need to do is to generate a unique application id for your Laravel application. To do that first you need to open up your GUI file explorer go inside your folder and copy .env.example to .env . It should look like this.

.env file

Now run php artisan key:generate from CLI tool/ terminal inside your project directory.

Artisan command to generate a key for the application

Now you are ready to run your application. And to do that type and enter php artisan serve from your terminal.

Serving the app on the local machine

And voila! your app is running on this local IP address. On my case which it’s running on http://127.0.0.1:8000 . Now open up your favorite browser and type in the url http://127.0.0.1:8000 .

Congratulations! your application is ready to rock and roll.

And your starter application

This is just a basic laravel application so there’s not much to it. So in the next tutorial, we’ll Install Homestead and discuss how to use homestead with your laravel application. Connecting MySQL database and folder structure of laravel.

Share this post

Subscribe to our newsletter