How to get all the users except current logged in user in Laravel

  918 views   8 months ago Laravel

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]);

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]