jcicero518
6/6/2018 - 5:22 PM

Laravel View Composer

Example of view composer in Route Service Provider. Defines a group of routes based on their name and passes it through to the "master" file. Any ->with() key becomes global for the view.

Then it can be used to start something like breadcrumbs.

public function boot() {
		view()->composer( 'layouts.master', function( View $view ) {
			$ticketRoutes = [
				'admin.tickets.index',
				'admin.tickets.create',
				'admin.tickets.update',
				'admin.tickets.foruser'
			];
			$userRoutes = [
				'admin.users.index',
				'admin.users.create',
				'admin.users.edit'
			];
			$clientRoutes = [
				'admin.clients.index',
				'clients.show'
			];
			$allRoutes = json_encode( array_merge( $ticketRoutes, $userRoutes, $clientRoutes ) );
			$view->with( 'routeName', $this->currentRouteName() )
			     ->with( 'ticketRoutes', $ticketRoutes )
			     ->with( 'userRoutes', $userRoutes )
			     ->with( 'clientRoutes', $clientRoutes )
			     ->with( 'allRoutes', $allRoutes );


		});

		parent::boot();
	}
<ul class="navbar-nav navbar-sidenav" id="sidebarLeft">
  <li class="nav-item dropdown {{ ($routeName === 'admin.tickets.create') ? 'active' : '' }}">
    <a class="nav-link dropdown-toggle" href="#">Tickets</a>
    
    <div class="dropdown-menu">
      <a class="dropdown-item">Child item 1...</a>
      <a class="dropdown-item">Child item 2...</a>
      <a class="dropdown-item">Child item 3...</a>
    </div>
  </li>
</ul>
<div class="breadcrumbs">
  <span class="fa fa-home" aria-hidden="true"></span>
  {{ \Illuminate\Support\Str::ucfirst( $routeName ) }}
</div>

// at the bottom, use @json to override Blade handling
<script>
	var routeName = @json($routeName);
</script>
<script src="{{ asset('js/app.js') }}"></script>
</body>