【问题标题】:Is it possible to pass 2 variables to a view in View Composers?是否可以将 2 个变量传递给 View Composers 中的视图?
【发布时间】:2021-04-26 22:03:19
【问题描述】:

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

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

【问题讨论】:

    标签: laravel variables


    【解决方案1】:

    您正确地传递了变量!

    问题是您只在if-structure 中定义了$catimg。 当isset($catalog-&gt;img)false 时,您将不得不考虑这种情况。

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

    【讨论】:

    • 感谢您的回答!是的,我也想通了。在我的 Google Drive 中,每个类别的图像都将被存储,现在我想为每个类别获取一个图像,为此,有一段带有 $catimg 的代码,它会工作吗?我为主要问题添加了一个视图。
    猜你喜欢
    • 2014-08-13
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多