简体   繁体   中英

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. How can I accomplish that?

While the accepted answer works, a nicer approach would be to make use of Laravel's except() Collection method :

The except method returns all items in the collection except for those with the specified keys

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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