How I get users which are created by Auth::user

I have two table users and customer_details. I want to get users which are created by Auth::user(). The created_by column is in customer_details table.

User Table

|  id  |  name     |      email      |  status  |
|  1   |   Admin   | <a href="" class="__cf_email__" data-cfemail="4021242d292e00252d21292c6e232f2d">[email protected]</a> |  Active  |
|  2   | Customer  | <a href="" class="__cf_email__" data-cfemail="3e4b4d5b4c7e5b535f5752105d5153">[email protected]</a>  |  Active  |

CustomerDetails Table

|  id  |  user_id  |  added_by  |  address  |
|  1   |     2     |     1      |  NY City  |

This is my query

$customers = User::role('Customer')->whereIn('status', ['Active'])->get();

Want to get records where added_by is current auth user


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

$customers = User::role('Customer')->whereIn('added_by', Auth::id())->get();

I think this should help

here we are using Auth::id() to get the id of the current user and then using eloquent to search for it.

I am considering that here added_by column contains the ID;

Method 2

Create a relation in your CustomerDetail model:

public function addedBy()
    return $this->belongsTo(User::class, 'added_by');

Then, you can query using this relation:

CustomerDetail::whereHas('addedBy', function($query) {
    return $query->where('id', auth()->id());

This query returns all customer created by the user current logged in.

To get all users with it’s customers created by the current logged in user, add a new relation, now to the user model:

public function customerDetail()
    return $this->hasOne(CustomerDetail::class, 'added_by');

and query users with customers created byt the logged in user:

User::role('Customer')->whereHas('customerDetail', function($query) {
  return $query->where('added_by', auth()->id());
->whereIn('status', ['Active'])

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x