【问题标题】:How to pass data from controller to view in Laravel如何将数据从控制器传递到 Laravel 中的视图
【发布时间】:2021-08-30 04:05:53
【问题描述】:

请帮助我。我有这 3 个表,我在如何根据 restaurant idControllerview 调用 category name 时遇到问题。提前谢谢你。

items

categories

restorant

这是我的Controller

public function index()
{

    if (auth()->user()->hasRole('owner')) {
        $items = Items::with('category')->get();
        $restorant_id = auth()->user()->restorant->id;
        $category = Categories::where(['restorant_id' => $restorant_id]);
    }

    return view('point-of-sale::index', [
        'category' => $category,
        'items' => $items,
    ]);
}

【问题讨论】:

    标签: laravel view controller laravel-8


    【解决方案1】:

    如果您将get() 添加到$category = Categories::where(['restorant_id' => $restorant_id]); 语句的末尾,您将返回一个Eloquent 集合:

    $category = Categories::where(['restorant_id' => $restorant_id])->get();
    

    $category 变量传递给您当前的视图,考虑将其重命名为$categories,尽管只是为了推断可能有多个。

    然后在您的view 中,您可以遍历Category 结果并访问name 属性:

    @forelse ($category as $cat)
      {{ $cat->name }}
    @empty
      No categories.
    @endforelse
    

    更新

    如果您想通过他们的category_id 获得items,您可以像使用$categories 那样做:

    $items = Items::where(['category_id' => $category_id])->get();
    

    或者,如果您的 Categories 模型上有 items 关系,您可以通过这种方式访问​​它们:

    $category = Categories::with('items')
        ->where(['restorant_id' => $restorant_id])
        ->get();
    

    上面将急切加载与category 相关的items,然后您可以在视图中访问它,例如:

    @forelse ($category as $cat)
      {{ $cat->name }}
    
      @foreach ($cat->items as $item)
        {{ $item->name }}
      @endforeach
    
    @empty
      No categories.
    @endforelse
    

    【讨论】:

    • 感谢您的帮助!请问,我需要用同样的方法调用Items基于category_id吗?
    • @cdogol 我已经添加了几个示例来回答您如何访问与categories 相关的items
    • 为什么会出现这个错误? Property [items] does not exist on this collection instance.
    • @cdogol 我假设您在 Categories 模型上有一个名为 items 的关系。如果该关系不存在,您将收到错误消息,请查看eloquent relationships 文档了解更多信息,
    • 我有,return $this->hasMany(\App\Items::class, 'category_id', 'id');
    猜你喜欢
    • 2017-01-29
    • 2015-07-25
    • 2018-04-11
    • 2019-04-15
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 2017-09-03
    相关资源
    最近更新 更多