Reputation: 13
So, I have the following Tables named:
ALBUMS(id, name, shared, group_id, user_id)
GROUPS(id, name, user_id)
GROUP_USER(group_id, user_id)
What I want to do is, using Laravel Eloquent to get the results of a query by checking if the AUTHENTICATED user is a member of the GROUP owned by the ALBUM.
Album Model:
public function groupSecurity()
{
return $this->belongsTo(Group::class, 'group_id');
}
Group Model:
public function ownedBy()
{
return $this->belongsTo(User::class, 'user_id');
}
public function members()
{
return $this->belongsToMany(User::class, 'group_user');
}
Thank you for your help :)
Upvotes: 1
Views: 61
Reputation: 2147
You can do like this:
$album = Album::whereHas('groupSecurity', function ($query) {
$query->whereHas('members', function($query2){
$query2->where('user_id', auth()->user()->id);
})->where('user_id', auth()->user()->id);
})->first();
So you search for one album that has a groupSecurity
which has in his members
the auth user and also it's owned
by the auth user.
If a record match this conditions $album
will have an instance of Album model, if not it will be null so you can do:
if($album){
// AUTHENTICATED user is a member of the GROUP owned by the ALBUM
}
Upvotes: 2