【问题标题】:Laravel I want to display only employees in tableLaravel我只想在表格中显示员工
【发布时间】:2020-12-26 19:05:49
【问题描述】:

您好,我正在构建一个人力资源管理系统,我想在数据表中只显示不是管理员的用户,但我遇到了错误,不知道我可能做错了什么。这是我的代码;

 <table class="table table-hover">
    <thead>
      <th>Username</th>
      <th>Department</th>
      <th>Salary</th>
    </thead>
    <tbody>
        @foreach($this->$users()->get() as $user)
        @if($user->is_admin !== 1)
        <tr>
          <td>{{$user->username}} </td>
          <td>{{$user->department}} </td>
          <td>{{$user->salary}} </td>
        </tr>
        @endif
        @endforeach
    </tbody>

表格

 Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->boolean('is_admin')->nullable();
            $table->string('department')->nullable();
            $table->integer('salary')->nullable();
            $table->string('image',255)->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

【问题讨论】:

  • 你能分享一下你的控制器吗?通常你不希望在你的视图中进行任何查询。
  • "但我遇到了错误" 那会是什么错误?仅供参考,从您的表 (-&gt;where('is_admin', '!=', 1)) 中获取“非管理员”用户比遍历 所有 用户要高效得多。另外,$this-&gt;$users() 应该是 $this-&gt;users()
  • 此代码应在控制器users()-&gt;get()..,并在is_admin上添加条件
  • 删除你在视图中添加的foreach循环,所有这些代码最好只添加到控制器并作为变量传递给视图。

标签: php mysql laravel laravel-5 laravel-7


【解决方案1】:

你可以试试@continue跳过循环

<table class="table table-hover">
    <thead>
        <th>Username</th>
        <th>Department</th>
        <th>Salary</th>
    </thead>
    <tbody>
        @foreach($this->$users()->get() as $user)
        @php
        if($user->is_admin == 1){
        @continue
        }
        @endphp
        <tr>
            <td>{{$user->username}} </td>
            <td>{{$user->department}} </td>
            <td>{{$user->salary}} </td>
        </tr>
        @endforeach
</tbody>

【讨论】:

    【解决方案2】:

    您可以通过仅选择一开始不是管理员用户的用户来扩展查询,而不是遍历用户表并检查每个用户以查看他们是否是管理员用户。

    where('is_admin', '!=' 1)
    

    这样您就已经拥有了所有想要显示的用户,并且您不必在视图中添加额外的逻辑。

    【讨论】:

      【解决方案3】:

      我忘记在控制器中编写代码

       public function addEmployee()
              {
                  $users = User::all();
                  return view('admin/addEmployee')->with('users',$users);
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-18
        • 2015-10-11
        • 2014-03-21
        • 1970-01-01
        • 1970-01-01
        • 2012-08-23
        • 2015-10-19
        • 1970-01-01
        相关资源
        最近更新 更多