How to use view composer in laravel ?

View Composer is commonly used to share some common variables across the multiple views. We can simply check these variables are set or not in the views. If variable is shared to a view then we can access it and process in the view.

According to laravel documentation,

"View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location."

Sometime, we might need settings for the applications or some dynamic advertisement for our website. View composer allows us to share such variables in multiple views so that we can use the variables where necessary.

Let's take an example of application setting. We will create a view composer to share settings details from database to multiple views.

Database Schema and Seeder

At first, we will create setting migration with following command.

php artisan make:migration create_settings_table --create=settings

Above command will generate a create_settings_table migration inside database/migrations/ directory. We will add following columns to settings table.

title|phone|address|email

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateSettingsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('settings', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('phone');
            $table->string('address');
            $table->string('email');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('settings');
    }
}

Also Read: Generating dummy data with faker in laravel

Now, let's create a seeder file to add some data to settings table. Run following command to create seeder.

php artisan make:seeder SettingTableSeeder

Above command will create a file SettingTableSeeder.php inside database/seeders/ directory. We will add data insertion code inside run function of the seeder. After that, we can register seeder to database seeder so that we can execute the seeder with artisan console command.

<?php

use Illuminate\Database\Seeder;

class SettingTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table("settings")->insert([
            'title'=>'Stack Learning',
            'phone'=>'3484544',
            'address' => 'Kathmandu',
            'email'=>'example@stacklearning.com'
        ]);
    }
}

In order to register this seeder, add following code inside run function of Database Seeder.

$this->call(SettingTableSeeder::class);

Now, we can run php artisan db:seed command to save these setting details to database.

Creating View Composer and Service Provider

We have already created database table for settings and seeder as well to save data to settings table. Now, we will create a view composer inside app/ViewComposer/ directory.

<?php

namespace App\ViewComposers;

use Illuminate\View\View;

class SettingComposer
{
    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $view->with('setting', \DB::table('settings')->first());
    }
}

Also Read: Using helper function in laravel

In order to compose a variable setting , we can use compose function as shown in above code. We use first column of settings table as setting variable. In order to share the setting variable to views, we need service provider. Let's create SettingServiceProvider with following command.

php artisan make:provider SettingServiceProvider

Above command will create a service provider inside app/Providers/ directory.

<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class SettingServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        View::composer(
            '*', 'App\ViewComposers\SettingComposer'
        );
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

We can use SettingComposer to compose setting variable. We use SettingComposer inside boot function so that we can share composed variable setting to multiple views. If we need to share the variable to all views, then we can simply put * over there. In order to share the variable to certain views only, we can customize the view composer code in above boot function.

Usage

It's quite easy to use the shared variable in the views. This is all you need to do.

@if(isset($setting))
     {{$setting->title}}
@endif


share :

Sagar Gautam

A Computer Engineer from Nepal.


Leave your Feedback