Return 如果未在数据库中设置,则查看变量 = null

Return view with variable = null if not set in database

我有一个问题。如果 DB 中没有记录,我如何 return 使用为空的变量查看。 我知道 return $variable ??无效的; 但我在视图中需要这个。

public function shop_items($shelf)
{
    $shop_shelf = $this->getTreeItems(0);
    $shop_items = DB::table("shop_items")->where('shelf_id', $shelf)->get();
    return view('shop',compact('shop_items','shop_shelf'));
}

如果有记录,我得到 $shop_items 的值,但如果没有这样的记录,我得到未定义的偏移量:0

编辑: 添加 shop.blade

@if(isset($shop_shelf))
@foreach($shop_shelf as $ss)
    <ul>
        <li>{{$ss["title"]}}
            @if(is_array($ss["children"]))
                <ul>
                    @foreach($ss["children"] as $sc)
                        <li>
                            <a href="/shop/shelf/{{$sc["id"]}}">
                                {{$sc["title"]}}
                            </a>
                        </li>
                    @endforeach
                </ul>
            @endif
        </li>
    </ul>
@endforeach

enter image description here

无法post所有代码所以我放了一张shop.blade

的图片

您可以使用

@forelse($shop_shelf as $ss)
    <ul>
        <li>{{$ss["title"]}}
            @if(is_array($ss["children"]))
                <ul>
                    @foreach($ss["children"] as $sc)
                        <li>
                            <a href="/shop/shelf/{{$sc["id"]}}">
                                {{$sc["title"]}}
                            </a>
                        </li>
                    @endforeach
                </ul>
            @endif
        </li>
    </ul>
@empty
    <p>No data to display</p>
@endforelse

PS : apply the @forelse loop structure wherever you have an array in your blade

docs