samedi 31 mars 2018

Laravel View Composer with View Component and One To Many Relationship

In short, I am wondering if there is a better way of using view composers than my current setup.

I have a ComposerServiceProvider with the following boot() code:

view()->composer(['components.carousel'], function ($view) {
    $carousels = Carousel::with('slides')->get();
    $view->with(compact('carousels'));
});

My component is pretty straightforward:

<style type="text/css">
  .carousel-item {
    height: 100vh;
    min-height: 300px;
    background: no-repeat center center scroll;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
  }
  .carousel-caption {
    background-color: rgba(0,0,0,0.1);
    top: 40%;
    bottom: unset;
  }
</style>

@php
  $carousel = $carousels->filter(function ($carousel, $key) use ($name) {
    return ($carousel->name == $name);
  });
@endphp

<header>
  <div id="carouselIndicators" class="carousel slide" data-ride="carousel">
    <ol class="carousel-indicators">
      @foreach ($carousel[0]->slides as $slide)
        <li data-target="#carouselIndicators"
            data-slide-to=""
            class=""></li>
      @endforeach
    </ol>
    <div class="carousel-inner" role="listbox">
      @foreach ($carousel[0]->slides as $slide)
        <div class="carousel-item "
             style="background-image: url('')">

          @if ($slide->title || $slide->description || $slide->link)
            <div class="carousel-caption d-none d-md-block">
              <h3></h3>
              <p></p>
              <a class="btn btn-primary btn-sm" href="">Learn More</a>
            </div>
          @endif

        </div>
      @endforeach
    </div>
    <a class="carousel-control-prev" href="#carouselIndicators" role="button" data-slide="prev">
      <span class="carousel-control-prev-icon" aria-hidden="true"></span>
      <span class="sr-only">Previous</span>
    </a>
    <a class="carousel-control-next" href="#carouselIndicators" role="button" data-slide="next">
      <span class="carousel-control-next-icon" aria-hidden="true"></span>
      <span class="sr-only">Next</span>
    </a>
  </div>
</header>

To use the component:

@component('components.carousel', [
    'name' => 'Super Awesome Carousel'
])
@endcomponent

What is bothering me is this piece:

@php
  $carousel = $carousels->filter(function ($carousel, $key) use ($name) {
    return ($carousel->name == $name);
  });
@endphp

I am returning every carousel WITH the slides relationship and then filtering the carousels and only using the one carousel->slides relationship I need. Is there a way of letting the view composer know the name of the carousel I need? Or is there a better way of approaching this?

Thanks,



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2H1Mqr1
via IFTTT

Aucun commentaire:

Enregistrer un commentaire