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

adamjhn's avatar

query to to get the email of all users that did a registration in a specific conference is not working

I want to do a query using eloquent that gets the email of all users that did a registration in a specific conference. The email is stored in the users table. The registrations table has the column "user_that_did_the_registration", this column has the id of the user that did the registration.

So I have this code below but "$usersEmail[] = $user->email;" shows "Trying to get property of non-object". Do you know why?

public function sendEmail(Request $request, $id){

    $users = User::with('conferences.registrations', 'registrations.customer')->find($conferenceID);
    $usersEmail = [];
    // dd($users);
    foreach($users as $user){
        $usersEmail[] = $user->email;
    }
}

With code below it shows an empty collection "Collection {#280 ▼ #items: []}":


$users = User::whereHas('registrations', function ($query) use($id) {
    $query->where('conference_id', '=', $id);
})->get();

But it works with static "1" like:


$users = User::whereHas('registrations', function ($query){
    $query->where('conference_id', '=', 1);
})->get();

Relevant relationships for the question:

Users model:

public function registrations(){
    return $this->hasMany('App\Registration','user_that_did_registration');
}

Registration model:

public function customer(){
    return $this->belongsTo(User::class, 'user_that_did_registration', 'id');
}
 public function participants(){
    return $this->hasMany('App\Participant');
}

public function conferenec(){
    return $this->belongsTo('App\Conference');
}

Conference Model:

 public function registrations(){
    return $this->hasMany('App\Registration', 'conference_id');
}
0 likes
3 replies
Snapey's avatar

if you use find then only one model is returned

in this case, the user that matches the conferenceid (wherever that dame from?)

The correct approach is via relationships

eg (not adapted for your code)

$users = Registration::find($id)->users();
1 like
adamjhn's avatar

Thanks, like that it appears "Call to undefined method Illuminate\Database\Query\Builder::users()". With " $users = Registration::find($id)->customer(); " dont appears that error.

But also that query dont show the necessary results, because is necessary to use the conference id, because is to get the users that did a registration in a specific conference.

_Artak_'s avatar
_Artak_
Best Answer
Level 14

$users = User::whereHas('registrations', function ($query) use($id) {
    // $query - registrations 
    $query->whereHas('conferenec', function($q) use ($id) {
        $q->where('id', '=', 1);
    });
})->get();


foreach ($users as $key => $user) 
{
    echo $user->email;
}


1 like

Please or to participate in this conversation.