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 = [
			$userRoutes = [
			$clientRoutes = [
			$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 );


<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 class="breadcrumbs">
  <span class="fa fa-home" aria-hidden="true"></span>
  {{ \Illuminate\Support\Str::ucfirst( $routeName ) }}

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