-3

I want to select users that have a referral username and role of  4 in the users table and store them in $refUser but am getting this error. "Illuminate\Database\Eloquent\Collection {#440 ▼ #items: [] }"

  $new_ref_user = $user->referal;
            $itr_cnt = 0;    

            while ($itr_cnt <= $ref_cnt-1)
            {
                $refUser = User::where('username', $new_ref_user)->where('role', 4)->get();
                dd($refUser);
                if(count($refUser) > 0)
                {
                    $ref = new ref;
                    $ref->user_id = $user->id;
                    $ref->username = $new_ref_user;

Please, what am doing wrong? Thanks for your help

Job Shork
  • 1
  • 2

1 Answers1

0

dd means "dump and die". You're not receiving an error, you're seeing the result of your dd($refUser) call. Illuminate\Database\Eloquent\Collection {#440 ▼ #items: [] } is an empty collection.

Rather than querying the database inside a loop, you can use one query to get all users at once, then loop through those users instead. I don't know where $ref_cnt-1 is in your code and why you have a loop at all, but you can do something like this. Also, check the spelling. Should it be referral or is the var spelled incorrectly? And is ref the name of a model class? I would suggest going with the name UserReferral instead.

If $user->referral is an array:

User::whereIn('username', $user->referral)
    ->where('role', 4)
    ->get()
    ->each( function ($ref) use ($user) {
       $model = new UserReferral;
       $model->user_id = $user->id;
       $model->username = $ref->username;
       $model->save();
   }); 

If $user->referral is just a string (username):

$ref = User::where('username', $user->referral)->first();
if ($ref) {
    $model = new UserReferral;
    $model->user_id = $user->id;
    $model->username = $ref->username;
    $model->save();
}

Note that $query->get() returns a Collection and $query->first() returns the first matching row (in a model instance if using Eloquent).

Erin
  • 5,315
  • 2
  • 20
  • 36