Sharing Data With Multiple Views View Composer
Using of view composer to share data with multiple views#
today we will see how view composer works we can share as much data with mulitple views without manually passing each time for each view from controller.
old approch#
what we are doing is we are manually passing data to view from controller like below .
public function dashboard(){
$states = ["New York", "Georgia", "Dallas"];
$categories = ["Restaurants", "Bars", "Bakeris", "Cafes"];
return view("frontend.dashboard.index",compact("states","categories"));
}
but suppose you have more that 10 views which all needs states and categories data, then you have to do above 10 time that is not a best practice.
Best approach#
we will use view composer inside the AppServiceProvider's
boot()
method.
modify your AppServiceProvider.php class file like below
namespace App\Providers;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\ServiceProvider;
/**
* Class AppServiceProvider.
*/
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// ..... old code will remain same
View::composer(['frontend.new.*'], function ($view){
$states = ["New York", "Georgia", "Dallas"];
$categories = ["Restaurants", "Bars", "Bakeris", "Cafes"];
$view->with(['states' => $states, 'categories' => $categories]);
});
}
}
View::composer()
first argument is array which is view location we can use wild card *
for multiple views in folder like in example frontend.new.*
will consider all the files inside new folder will receive $state
and $categories
variable.
Problem#
problem will arise when you will use database query inside the View::composer
it will call that query for each view which result in multiple query execution, which is not good.
so to overcome this problem we can user Caching
technique like below.
public function boot()
{
// ..... old code will remain same
View::composer(['frontend.new.*'], function ($view){
$states = \Cache::rememberForever('states', function () {
$stateData = States::all();
return $stateData;
});
$categories = \Cache::rememberForever('categories', function () {
return Categories::all();
});
$view->with(['states' => $states, 'categories' => $categories]);
});
}
Once Cache::rememberForever()
is cached it will remember the data forever, there is other method called remember()
which uses second argument which is time for cache renewing but we will cover that in some another post.
for clearing cache we can execute php command like below.
php artisan cache:clear