Feb 20, 2021
0
Level 1
Get nested relationship where use belongs to page and has the correct roles
So, I am trying to check if a user belongs to a page that owns a job.
The relationships are like so:
user.php
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function pages(): BelongsToMany
{
return $this->belongsToMany(Page::class);
}
page.php
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class);
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function jobs(): HasMany
{
return $this->hasMany(Job::class);
}
job.php
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function page(): BelongsTo
{
return $this->belongsTo(Page::class);
}
Now, I want to see if a user belongs to a page that owns the job:
$job = Job::find(1); //belongs to page_id 1, has job_id 1
$user = User::find(1); // only owns 1 page and 1 job.
I can change my Job::find(1) to any idea, and the code below will always return true, even if User::find(1) doesn't belong to a page that owns that job
return $job->page->whereHas('users', function($query) use($user) {
$query->where('page_user.user_id', $user->id);
$query->whereIn('page_user.role', ['admin', 'editor']);
})->exists();
What am I doing wrong?
Please or to participate in this conversation.