35
votes

I am doing:

    User::all();

to get all the users from users table. I want to select all the users except current logged in user. How should I do that? something like,

    User::where('id','!=',$currentUser->id)->get();

Thanks in advance!

5

5 Answers

50
votes

You can get the current user's id with auth()->id(). Then pass that to the query:

$users = User::where('id', '!=', auth()->id())->get();
66
votes

Using except() will accomplish the same thing a little more fluently:

$users = User::all()->except(Auth::id());

...or, since you already have the User id:

$users = User::all()->except($currentUser->id);
8
votes

If you are using the Auth helper, use this.

User::where('id', '!=', Auth::user()->id)->get();
0
votes
Use Auth;
Use App\User;

public function index()
$id = Auth::id();
$result = User::where('id', '!=', $id)->get();
dd($result);
0
votes
App\Models\User::whereKeyNot(auth()->id)->get()

Using 'except' actually retrieves ALL users, then performs an extra operation on the collection to remove the current user, which is not as effective.