首页 > 解决方案 > 是否可以将 2 个变量传递给 View Composers 中的视图?

问题描述

我正在尝试将 2 个变量传递给 View Composers,如下所示:

public function compose(View $view)
  {
      $catalog = Category::with('children')->where('parent_id', NULL)->get();
      //
      if(isset($catalog->img)){
        // $cat = Category::
        $contents = collect(Storage::disk('google')->listContents('sdfJSALSNldKdnslwk230jsd/', false));
        $file = $contents
        ->where('type', '=', 'file')
        ->where('filename', '=', pathinfo($catalog->img, PATHINFO_FILENAME))
        ->where('extension', '=', pathinfo($catalog->img, PATHINFO_EXTENSION))
        ->first();
      $catimg = isset($file['path'])?(Storage::disk('google')->exists($file['path'])?Storage::disk('google')->url($file['path']):NULL):NULL;
      };
      //
      return $view->with(['catalog' => $catalog, 'catimg' => $catimg]);
  }

但我得到了错误:Undefined variable $catimg

也许这不是传递第二个变量的正确方法?

而且,在顶部我检查图像是否存在于数据库中,但在我看来这是错误的方式,因为那里只返回父元素,我如何检查每个类别是否有图像?可能需要通过foreach运行?

@foreach( $catalog as $item )
  <li class='has-sub'><a href="#"><img class="catalogimg" src="@isset($item->img){{Storage::url($catimg)}}@else /img/categories/kitchen-utensils.png @endisset"><span class="cat-text">{{ $item->name }}</span></a>
    <ul>
      @foreach( $item->children as $subitem )
        <li><a href='/{{ $item->url }}/{{ $subitem->url }}'><img class="catalogimg" src="@isset($subitem->img){{Storage::url($catimg)}}@else /img/categories/kitchen-utensils.png @endisset"><span class="cat-text">{{ $subitem->name }}</span></a></li>
      @endforeach
    </ul>
  </li>
@endforeach

标签: laravelvariables

解决方案


您正确地传递了变量!

问题是您$catimg仅在if-structure. 您将不得不考虑 is 的isset($catalog->img)情况false

在这种情况下,该类别不存在图像,并且if-structure不会输入,因此$catimg未定义。因此,如果设置了 $cat_img,您将必须检查您的视图文件,返回默认图像或禁止此操作。(或者只允许带有图像的类别)。


推荐阅读