首页 > 解决方案 > 尽管定义了变量,但未定义的变量?

问题描述

我的应用程序中的用户可以创建自己的组。组上显示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 还很陌生,所以我可能在这里遗漏了一些明显的东西?

标签: laravel

解决方案


您只定义$group了变量。joinedUsers是关系,您从未在任何地方将其定义为变量。你必须这样做

@foreach($group->joinedUsers as $user)
    {{$user->name}}
@endforeach 

推荐阅读