While working in Laravel authentication, sometimes you might need to get all users data except current logged user.

This is required when you want to update current user data, e.g. email, username etc. In this cases you might want to check if the email or username already exist or not. Also sometimes when logged user want to send message to other users, there you need to check that user don't send message to self.

This can be done by many ways, from model or DB query. Here we have showed few methods to get all users data except the current logged user.

You can get current user's id with auth()->id(), which you can pass in query.

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

If you are using Auth helper, you can use it.

$users = User::where('id', '!=', \Auth::user()->id)->get();

Using except() method will get the same response more dynamically:

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

With except() method, you can pass any number of ids to exclude users.

$users = User::all()->except([1,2,3,4]);

 


Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

OR

No Comments