laravel - 尽管定义了变量,但未定义的变量?
问题描述
我的应用程序中的用户可以创建自己的组。组上显示groups/show.blade.php
,其他用户可以加入该组。
我想显示所有加入每个组的人的列表。
在groups/show.blade.php
页面上我有以下内容
@if ($joinedUsers)
@foreach($joinedUsers as $joinedUser)
{{$user->name}}
@endforeach
@else
@endif
@endsection
我得到的错误是:
未定义变量:group_joined_user
这很奇怪,因为在我的Group
模型中我有
* Get the users that joined the group.
*/
public function joinedUsers()
{
return $this->belongsToMany(User::class, 'group_joined_user', 'group_id', 'user_id')
->withTimestamps();
}
和我的GroupController.php
public function show($id)
{
$group = Group::with('joinedUsers')->where('id', $id)->first();
return view('groups.show', compact('group'));
}
我的路线中有这个
Route::resource('groups', 'GroupsController');
我对 Laravel 还很陌生,所以我可能在这里遗漏了一些明显的东西?
解决方案
您只定义$group
了变量。joinedUsers
是关系,您从未在任何地方将其定义为变量。你必须这样做
@foreach($group->joinedUsers as $user)
{{$user->name}}
@endforeach
推荐阅读
- sql - SQL获取有序数据的排名
- html - 允许图像溢出父 div 但需要将内容向下推送
- react-native - 如何在 React Native 中选择正确的 gradle 版本
- monaco-editor - 如何在评论中为“待办事项”创建规则
- python - Python中的动态数据框转换
- ant - Apache ANT:get 不支持嵌套的“header”元素
- excel - 无效的过程调用或参数 excel - for 循环中的错误 5
- python - 从具有最多数据(非 NA)的三列创建组合列
- node.js - 使用 nodejs 获取 DNS 后缀
- python - 类中的意外缩进错误 __init__