Laravel: Load Posts With Privacy Only To Subscriber

- 1 answer

i have a view in which the posts from the database are loaded and displayed. Each post has a privacy that can be set by the user. If the privacy is 1, the post can be viewed by anyone. If the privacy is 2, the post may only be viewed by users who have subscribed to the user.

How can I show the posts with privacy 2 only to the subscriber and not to anyone?

Helper Class on UserModel

public function isFollowed()
    return $this->followers()
        ->where('follower_id', auth()->id())
        ->where('', 1)

Load Posts

$posts = Post::with('comments', 'tags')->whereIn('posts.privacy', [1, 2])->where('posts.status', 1)->where('posts.archived', 0)->where('posts.type', '!=', 7)->latest()->paginate(15);


You will simply have to make a distinction within the constraints. Because you have a few other constraints, it is necessary to put the OR joined constraints in their own where():

use Illuminate\Database\Eloquent\Builder;

$posts = Post::query()
    ->with('comments', 'tags')
    ->where('posts.status', 1)
    ->where('posts.archived', 0)
    ->where('posts.type', '!=', 7)
    ->where(function (Builder $query) {
        $query>where('posts.privacy', 1)
            ->orWhere(function (Builder $query) {
                $query->where('posts.privacy', 2)
                    ->whereExists(function ($query) {
                            ->whereColumn('followers.user_id', 'posts.user_id')
                            ->where('followers.follower_id', auth()->id())
                            ->where('', 1);

I wasn't too sure what the second column on your followers table is besides follower_id, so I assumed user_id. This most likely needs a change.

By the way, what you describe sounds more like visibility but not privacy. If I can subscribe to you (without restrictions and acceptance of yours) and I suddenly see more content of you, this is hardly privacy.