Reputation: 1458
The Comment
model has the following relationship set:
function replies(){
return $this->hasMany('App\Reply', 'comment_id', 'id')->whereNotNull('replies.status');
}
The replies()
needs to return the replies even if the status is null for the currently logged in user and not for the others. The others should see only replies that have status set (unless they are the owners in which case it should show to them)
I am having a tough time adding this logic to it; any help will be appreciated
Upvotes: 0
Views: 48
Reputation: 15616
You can look at model booting scopes, in your case you need to add a global scope inside the App\Reply
model class:
protected static function boot()
{
parent::boot();
static::addGlobalScope('guest_filter_for_comments', function (Builder $builder) {
return $builder->when(\Auth::check() == false, function ($query) {
return $query->whereNotNull('replies.status');
});
});
}
And when you want to disable the filter whenever needed, you can just use Comment::replies()->withoutGlobalScopes()
to retrieve unfiltered results when not authenticated.
BTW, You can use the same logic to filter out the comments related to the user. When you call Comment::all()
with doing this for the authenticated user, it will filter out the related comments automatically if you use a boot scope for your Comment
class.
https://laravel.com/docs/5.8/eloquent#global-scopes (Anonymous global scopes) https://laravel.com/docs/5.8/queries#conditional-clauses
Upvotes: 1