Reputation: 452
I have two table email (email_id, email) and users (user_id) with a pivot table user_email (id, user_id, email_id) and i would like to check the existence of my email "[email protected]" for my user_id "2".
$emailID = Email::where('email', '[email protected]')->pluck('id');
$exists = User::find('2')->emails->contains($emailID);
The result is ok, but i would like to know if it's possible to combine this into one query using Eloquent.
If have these models :
class Email extends Model {
public function users() {
return $this->belongsToMany('App\User', 'user_email');
}
}
class User extends Model {
public function emails() {
return $this->belongsToMany('App\Email', 'user_email');
}
}
Upvotes: 1
Views: 169
Reputation: 2358
You can make query with relationships too:
$email_address = '[email protected]';
$user_id = 2;
$email = Email::whereHas('users', function($q) use ($user_id) {
$q->where('users.id', $user_id);
})->where('email', $email_address)->first();
if($email->exists) {
//... it exists
}
Upvotes: 1
Reputation: 7447
Yes, you can do it like this.
public function getUserById($id) {
$user = User::with('emails')->where('id', 2)->first();
return view('your-view')->with('user', $user);
}
Then on your blade template.
@foreach ($user->emails as $email)
{{ $email->email }}<br/>
@endforeach
Check out the Eager Loading documentation for more information.
Upvotes: 1