Laravel 5 global variable in all views file


Here, i will let you know how to set global variable in laravel 5 application. In this article i will set globle variable two way on simple view share and another using composer view share.

As we know, every webiste or project there are several things are comman and access it in every page like footer text, logo, site title etc. So it is necessary to define it one time and access it on all views file.

So, In this example we will share varible from "AppServiceProvider.php", So let's see both example and use it.

Using View Share

app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider

{

/**

* Bootstrap any application services.

*

* @return void

*/

public function boot()

{

view()->share('siteTitle', 'HDTuto.com');

}

/**

* Register any application services.

*

* @return void

*/

public function register()

{

//

}

}

Using Composer

app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider

{

/**

* Bootstrap any application services.

*

* @return void

*/

public function boot()

{

view()->composer('*', function ($view) {

$view->with('siteTitle', 'HDTuto.com');

});

}

/**

* Register any application services.

*

* @return void

*/

public function register()

{

//

}

}

Now we can simple access $siteTitle varible like as bellow used :

How to use:

{{ $siteTitle }}

I hope you found your solution....


July 16, 2017 | 265 Viewer | Category : PHP Laravel
Related Posts:



Blog Search