I usually use View Composers so it's more clear and readable.
For example If I want to share a variable with the main navbar to all of my views I follow the below rules:
1. Create new service provider
You can create a service provider with artisan cli:
php artisan make:provider ViewComposerServiceProvider
In the ViewComposerServiceProvider file create composeNavigation method in which has the blade template main.nav-menu that represents the navmenu with shared variables.
The ViewComposerServiceProvider looks like:
<?php
namespace AppProviders;
use IlluminateSupportServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this->composeNavigation();
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
private function composeNavigation()
{
view()->composer('main.nav-menu', 'AppHttpViewComposersNavComposer');
}
}
2. Create Composer
As you saw in the file above we have AppHttpViewComposersNavComposer.php so let's create that file. Create the folder ViewComposers in the AppHttp and then inside create NavComposer.php file.
The NavComposer.php file:
<?php
namespace AppHttpViewComposers;
use AppRepositoriesNavMenuRepository;
use IlluminateViewView;
class NavComposer
{
protected $menu;
public function __construct(NavMenuRepository $menu)
{
$this->menu = $menu;
}
public function compose(View $view)
{
$thing= $this->menu->thing();
$somethingElse = $this->menu->somethingElseForMyDatabase();
$view->with(compact('thing', 'somethingElse'));
}
}
3. Create repository
As you saw above in the NavComposer.php file we have repository. Usually, I create a repository in the App directory, so create Repositories directory in the App and then, create inside NavMenuRepository.php file.
This file is the heart of that design pattern. In that file we have to take the value of our variables that we want to share with all of our views.
Take a look at the file bellow:
<?php
namespace AppRepositories;
use AppThing;
use DB;
class NavMenuRepository
{
public function thing()
{
$getVarForShareWithAllViews = Thing::where('name','something')->firstOrFail();
return $getVarForShareWithAllViews;
}
public function somethingElseForMyDatabase()
{
$getSomethingToMyViews = DB::table('table')->select('name', 'something')->get();
return $getSomethingToMyViews;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…