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();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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');
}
$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;
}
Please or to participate in this conversation.