如何将数据从控制器传递到 Laravel 中查看
How to pass data from controller to view in Laravel
请帮助我。我有这 3 个表,我有关于如何根据 restaurant id
从 Controller
到 view
调用 category name
的问题。提前谢谢你。
Table items
Table categories
Table 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,
]);
}
如果您将 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
请帮助我。我有这 3 个表,我有关于如何根据 restaurant id
从 Controller
到 view
调用 category name
的问题。提前谢谢你。
Table items
Table categories
Table 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,
]);
}
如果您将 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