1 month ago

Accessing model properties in scope

Posted 1 month ago by ExpDev07

Hey, I wish to scope posts of users that have not blocked each other, for this I try the following model:

class Post extends Model

    protected $fillable = [

     * Gets the user that made the post.
     * @return BelongsTo
    public function user(): BelongsTo
        return $this->belongsTo(User::class);

     * Scope a query to exclude posts where the provided user has been blocked by the creator or
     * the creator blocked by the user.
     * @param Builder $query
     * @param User $user
     * @return Builder
    public function scopeNotBlocked($query, User $user): Builder
        // The user that created the post.
        $creator = $this->user; // = null

        // Query for posts where creator has not blocked the provided user or the user has blocked the creator.
        return $query->whereDoesntHave('user.blocks', function (Builder $query) use ($creator, $user) {
                ->where('user_id', $creator->id)
                ->orWhere('blocked_id', $user->id);


However, this doesn't work as $creator is null because we can't access model properties in scopes. How would I else achieve the same functionality?

Please sign in or create an account to participate in this conversation.