Laravel 从 2 个不为空的表中获取数据

Laravel get data from 2 tables where not null

我正在尝试从两个不同的表中获取一些数据,

现在看起来确实像这样:

但我不想显示空字段(Global-Moderator、Moderator 和 Proef-Moderator)。我怎样才能用这段代码做到这一点;

控制器:

public function ForumTeam()
    {
        $roles = Role::where('id', '>', '4')->orderBy('id', 'DESC')->get();
        return View::make('team')->with('roles', $roles);
    }

查看:

<div class="panel-group col-sm-offset-1 col-sm-10">
  @foreach($roles as $role)
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">{{ $role->name }}</h3>
      </div>
      <div class="panel-body">
        <ul class="list-group">

          @foreach($role->user as $user)
            <li class="list-group-item">
              <img src="{{ Config::get('app.url') }}/public/img/avatar.jpg" style="float:left;margin-right:15px;padding-bottom:5px;" class="img-circle" alt="{{ $user->username }}" width="75" height="75">
              <h4 style="color:{{ $role->colour }};"><strong>{{ $user->username }}</strong></h4>
              <p>{{ $user->usertitle }}</p>
            </li>
          @endforeach

        </ul>
      </div>
    </div>
  @endforeach
</div>

所以我想隐藏未填写的字段,应该如何正确隐藏?

我的另一个选择是在 'empty' 字段中显示一些文本。喜欢 'There is nobody with this rank'.

谢谢!

您可以在第一个 @foreach 之后添加一个 if 语句来检查角色是否 有用户,

@foreach($roles as $role)
    @if(isset($role->user))
    ...
    @endif
@endforeach

您can/should可以使用:

@foreach($roles as $role)

   @if($role->user != null || !empty($role->user->name))

   @endif

@endforeach

然后您可以检查 role->user 是否为 NOT NULL 或角色名称是否不是 empty.WHERE name 是角色名称,即 "Admin", "Moderator"

或者,尝试:

  @foreach($roles as $role)

    @if(count($role->user) >= 1)
       // Do stuff
    @endif

  @endforeach

由于您得到的 User 具有一对多关系,因此会有多个用户。