php - LARAVEL how to hide some of the relationship records?

For example, you havePost
&Comments
andPost
can have multiple comments, but the given user can only see specific comments. How this can be done?
Let's imagine a situations where we have a user, post and comments, and the given user can see only comments their friends are created.
// Post.php
public function comments()
{
return $this->hasMany(Comment::class);
}
// User.php
public function friends()
{
return $this->hasMany(Friend::class);
}
// CommentPolicy.php
public function view(User $user, Comment $comment)
{
return $user->friends->pluck('id')->contains($comment->created_by_id);
}
So, when we run$post->comments
- can we run that policy on each record?
Answer
Solution:
You can use global scopes or local scopes to define sets of constraints:
/**
* Scope a query to only include popular comments.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}
Usage:
$post->comments()->popular()->get();
Answer
Solution:
Either you can use scopes as mentioned in the other answer to this question.
or you may use filters in the relationship itself in following way:
public function comments()
{
return $this->hasMany(Comment::class)->where('is_visible', true);
}
It will fetch all comments against the post which hasis_visible
set totrue
Hope this will help you.
Best.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: uncaught error: call to undefined function mysqli_connect()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.