laravel - 是否可以将 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
解决方案
您正确地传递了变量!
问题是您$catimg
仅在if-structure
. 您将不得不考虑 is 的isset($catalog->img)
情况false
。
在这种情况下,该类别不存在图像,并且if-structure
不会输入,因此$catimg
未定义。因此,如果设置了 $cat_img,您将必须检查您的视图文件,返回默认图像或禁止此操作。(或者只允许带有图像的类别)。
推荐阅读
- sql - SQL:如何设计版本化的键:值对,允许非唯一值?
- ruby-on-rails - 将html输入转换为erb
- r - 重塑数据框,以便匹配的家庭成员拥有自己的列
- angular - 展开时 JAWS 无法从选择下拉列表中读取值
- c++ - 如何在 C++ 中删除指向指针的指针的内存
- r - 根据另一列中值的单次出现,如何使列中的所有值相同?
- javascript - 无法从获取请求 Node.js,Express 中获取对象
- sql-server - 如何从开发容器中连接到 SQL Server 数据库?
- java - 如何在 Java 中识别文件类型?
- c# - 在 ASP.NET Core 中使用 datetime 返回 http 500 错误