简体   繁体   English

当我登录时,我想在 Laravel 中查看除登录用户以外的所有用户信息?

[英]When I am logged in I want to see all users' information, other than the logged-in user, in Laravel?

home blade家用刀片

<div class="card-header">Total Users: {{ $users->count() }} </div>

<div class="card-body">
    @if (session('status'))
        <div class="alert alert-success" role="alert">
            {{ session('status') }}
        </div>
    @endif

    <table class="table table-dark table-striped">
        <tr>
            <th>SL</th>
            <th>Name</th>
            <th>Email</th>
            <th>Created at</th>
        </tr>
        @foreach($users as $user)
            <tr>
                <td>{{$loop->index +1}}</td>
                <td>{{ $user-> name}}</td>
                <td>{{$user->email}}</td>
                <td>{{$user->created_at->diffForHumans()}}</td>
            </tr>
     @endforeach
   </table>
</div>

HomeController家庭控制器

public function index()
{
    $users =  User::all();
    return view('home', compact('users'));
}

When I am logged in I want to see all the other users information in a table other than the logged-in user in Laravel.当我登录时,我想在 Laravel 中的登录用户以外的表中查看所有其他用户信息。 How can I accomplish that?我怎样才能做到这一点?

While the accepted answer works, a nicer approach would be to make use of Laravel's except() Collection method :虽然接受的答案有效,但更好的方法是使用 Laravel 的except()集合方法

The except method returns all items in the collection except for those with the specified keys除了具有指定键的项目外,except 方法返回集合中的所有项目

Your query then just returns all users except the currently logged in user to your view.然后,您的查询只会将除当前登录用户之外的所有用户返回到您的视图中。 No logic in your view, no other changes required:您认为没有逻辑,不需要其他更改:

public function index()
{
    $users =  User::all()->except(Auth::id);
    return view('home', compact('users'));
}

If you pass the current user's ID along with the user list you can simply test against that ID.如果您将当前用户的 ID 与用户列表一起传递,您可以简单地针对该 ID 进行测试。

public function index()
{
    $users =  User::all();
    return View::make('home', array(
      'users' => $users,
      'user_id' => Auth::id()  
    ));
}

@foreach($users as $user)
   @if ($user->id != $user_id)
     <tr>
       <td>{{$loop->index+1}}</td>
       <td>{{$user->name}}</td>
       <td>{{$user->email}}</td>
       <td>{{$user->created_at->diffForHumans()}}</td>
     </tr>
   @endif
@endforeach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM