I usually use View Composers to make it more understandable and understandable.
For example, if I want to share a variable with the main navigation bar to all my views, I follow the rules below:
1. Create a new service provider
You can create a service provider using artisan cli:
php artisan make:provider ViewComposerServiceProvider
In the ViewComposerServiceProvider file, create the composeNavigation method, which has the main menu of the blade template main.nav, which represents the navigation menu with common variables.
ViewComposerServiceProvider looks like this:
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class ViewComposerServiceProvider extends ServiceProvider { public function boot() { $this->composeNavigation(); } public function register() {
2. Create a composer
As you saw in the above file, we have App \ Http \ ViewComposers \ NavComposer.php, so let's create this file. Create the ViewComposers folder in App \ Http, and then create the NavComposer.php file.
File NavComposer.php:
<?php namespace App\Http\ViewComposers; use App\Repositories\NavMenuRepository; use Illuminate\View\View; 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 a repository
As you saw above in the NavComposer.php file, we have a repository. Usually I create a repository in the application directory, so I create the repository directory in the application, and then create the NavMenuRepository.php file.
This file is the heart of this design pattern. In this file, we must take the value of our variables, which we want to share with all our representations.
Take a look at the file below:
<?php namespace App\Repositories; use App\Thing; 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; } }