Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all the users except current logged in user in laravel eloquent

Tags:

php

mysql

laravel

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!

like image 651
Priyanka Avatar asked Jul 07 '14 14:07

Priyanka


People also ask

What is difference between GET and all in Laravel?

get() is used when you want to add queries and all() is used to get all data, without using any condition. Example of all(): $query = Project::all(); Example of get(): $query = Project::select('id', 'name')->where('name', '')->orderBy('id', 'desc')->get(); Follow this answer to receive notifications.

What is except in Laravel?

The except method will return all the key/value pairs in the collection where the keys in the collection are not in the supplied $keys array. Internally, this method makes a call to the "Illuminate\Support\Arr:except($array, $keys)" helper function.


2 Answers

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); 
like image 129
damiani Avatar answered Sep 20 '22 20:09

damiani


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

$users = User::where('id', '!=', auth()->id())->get(); 
like image 22
Joseph Silber Avatar answered Sep 19 '22 20:09

Joseph Silber