Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Wakanda's avatar
Level 10

How to query the database using a different field other than id

Hi devs,

I am trying to query a database using a custom field see code below

 if (!empty(auth()->user()->referred_by)) {
                    //get referrer user id
                    $referrer = User::where('affiliate_id', auth()->user()->referred_by)->get();
                    dd($referrer);
                    Earning::create([
                        'user_id' => $referrer->id,
                        'amount_earned' => $transaction->billing_total / 2,
                        'affiliate_id' => auth()->user()->referred_by,
                    ]);
                }

its returning an empty array

also tried

 public function getRouteKeyName()
    {
        return 'affiliate_id';
    }
``
0 likes
1 reply
piljac1's avatar
piljac1
Best Answer
Level 28

The query logic itself looks fine. Have you validated the content of auth()->user()->referred_by and matched it against all affiliate_id values in your database to see if it exists?

Also, you should use first() instead of get() to retrieve a single entry because after your query you're accessing the id property as you were expecting a single entry to be fetched.

1 like

Please or to participate in this conversation.