Default scope for Eloquent models?

Here is an example database table ( users):

id - int(11) auto_increment
name - varchar(100)
banned - int(1)

A column bannedis a boolean that is 0( false) by default. If the user has been banned, the value is equal 1.

I would like to exclude all blocked users from all requests by default . I could create a request scope and then use it everywhere. However, I would rather just enable this check by default.

I could also create my own newQuery-method, for example:

// Inside User-model, which extends Eloquent
public function newQuery($excludeDeleted = true)
{
    $builder = parent::newQuery($exludeDeleted);
    $builder->where('banned', '=', '0');
    return $builder;
}

. , , , , Eloquent.

, ?

+6
4

, .

// Quick example, not tested
class UserRepositoy { // You should create an interface and maybe super class for handling common cases like caching, find(), all() etc

    protected $include_banned = false;
    protected $model;

    public function __construct() // you can use DI here
    {
            $this->model = new User;
    }

    public function setIncludeBanned($bool)
    {
        $this->include_banned = $bool;
    }

    protected function includeBanned($query)
    {
        if ($this->include_banned) {
            return $query->where('banned', 1);
        }
    }

    public function find($id)
    {
        $res = $this->model->where('id', $id);

        $res = $this->includeBanned($res);

        return $res->get();
    }

}

, - , API . Laravel , , / . googling Laravel Design Pattern . .

- , .

+3

, banned_at deleted_at. , , , (, withTrashed), ( ).

+1

Why don't you use the config variable for this:

public function newQuery($excludeDeleted = true)
{
    $builder = parent::newQuery($exludeDeleted);
    if (Config::get('hide_banned_users', true) !== false) {
        $builder->where('banned', '=', '0');
    }
    return $builder;
}

and change the configuration value when you need to see banned users.

0
source

Laravel provides Global Scopes specifically for this purpose. From the docs:

class AgeScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        return $builder->where('age', '>', 200);
    }
}

class User extends Model
{
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new AgeScope);
    }
}
0
source

Source: https://habr.com/ru/post/1527196/


All Articles