$allusers = User::where('id', '<>', Auth::id() )
->where('status' , 1)
->whereRoleIs('broker')
->where('email_verified_at', '<>', NULL)
->where('mailforfollowers', 1)
->whereHas('broker',function($query) user ($request){
$query->where();//query condition
})->
->whereHas('follower',function($query) user ($request){
$query->where();//wuery condition
})->
->get();
Aug 4, 2022
10
Level 5
What is the correct way to use relation in query ?
'User' has one to many relation with 'Follower'.
I need to send email to all the followers of the auth user. what will be the correct query ?
User Model
public function followers()
{
return $this->hasMany(Follower::class, 'brokerid', 'id');
}
Follower Model
public function broker(){
return $this->belongsTo(User::class,'id','brokerid');
}
public function follower(){
return $this->belongsTo(User::class,'id','followerid');
}
Controller :
$allusers = User::where('id', '<>', Auth::id() )
->where('status' , 1)
->whereRoleIs('broker')
->where('email_verified_at', '<>', NULL)
->where('mailforfollowers', 1)
->get();
Any help ?
Level 122
also have a look at scopes. where('status',1) tells anyone new to the code ( or future you) nothing about what this means
you could convert this to a scope like
->activeSubscriber()
or whatever status 1 actually means ( also use enums or constants instead of magic numbers)
same for
->verifiedEmail()
instead of the existing ->where('email_verified_at', '<>', NULL)
Please or to participate in this conversation.