如果未在数据库中设置,返回变量为null的视图

问题描述 投票:0回答:1

我有一个问题。如果数据库中没有记录,如何返回变量为null的视图。我知道返回$ 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

edite:添加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

无法发布所有代码,所以我放置了shop.blade图片

laravel view null return undefined
1个回答
0
投票

您可以使用

@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:在您有array的任何地方应用@forelse循环结构您的刀片

请参见docs

© www.soinside.com 2019 - 2024. All rights reserved.