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
ddmeans "dump and die". You're not receiving an error, you're seeing the result of yourdd($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-1is in your code and why you have a loop at all, but you can do something like this. Also, check the spelling. Should it bereferralor is the var spelled incorrectly? And isrefthe name of a model class? I would suggest going with the nameUserReferralinstead.If
$user->referralis an array:If
$user->referralis just a string (username):Note that
$query->get()returns aCollectionand$query->first()returns the first matching row (in a model instance if using Eloquent).