Search code examples
phplaravelmodelconditional-statementseager-loading

Exclude records which does not meet condition in model in laravel


I have multiple tables and their models which they have relation with each other named : "users","posts","tags","comments".

I want to exclude data of deactive users from all of this models, and whenever any of this models has been called do not return users which are deactive

I don't want to exclude those "users" using eloquent or query builder in their controllers, I need to do this in model so it apply to all places which are using said models.

posts , comments and tags relation to users is :

 public function user()
 {
    return  $this->belongsTo('App\Models\User', 'user_id');
 }

I need something like this in related model:

$instance = $this->belongsTo('App\Models\User', 'user_id');
$instance->whereIsDeactive(0);//return active users only
return $instance;

And something like this in user model:

return $this->whereIsDeactive(0);

Is it possible and is there any way to accomplish this?


Solution

  • Thanks to @Adam I solved the issue using global scopes.

    This is IsDeactive global scope :

    namespace App\Scopes;
    
    use Illuminate\Database\Eloquent\Scope;
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Builder;
    
    class IsDeactiveScope implements Scope
    {
        /**
         * Apply the scope to a given Eloquent query builder.
         *
         * @param  \Illuminate\Database\Eloquent\Builder  $builder
         * @param  \Illuminate\Database\Eloquent\Model  $model
         * @return void
         */
        public function apply(Builder $builder, Model $model)
        {
            $builder->where('is_deactive', 0);
        }
    }
    

    And this is how to call it in user model:

    /**
         * The "booting" method of the model.
         *
         * @return void
         */
        protected static function boot()
        {
            parent::boot();
    
            static::addGlobalScope(new IsDeactiveScope());
        }
    

    I hope this solution help others.