laravel icon indicating copy to clipboard operation
laravel copied to clipboard

Scope integration on schema level

Open SEUH opened this issue 3 years ago • 0 comments

Hi,

it would be nice if there was a way to add a global scope to a schema model. I've scraped through the issues and found only one proposed way: by adding global scopes inside the Server::serving() function, but that's a bit counter intuitive.

Is this a feature that this package could need? I have the following idea:

  • "defining" Schema::$withScopes and Schema::$withoutScopes
  • checking in Schema::model() function for the withScopes array and add the scopes
  • checking in Schema::newQuery() function for $withoutScopes and remove the scopes

If not clear enough what i mean, here's corresponding code:

// laravel-json-api/eloquent/src/Schema.php

public function newQuery($query = null): JsonApiBuilder
    {
        $query = $query ?? $this->newInstance()->newQuery();
        
        if (property_exists(static::class, 'withoutScopes')) {
            $query = $query->withoutGlobalScopes(static::$withoutScopes);
        }
        
        return new JsonApiBuilder(
            $this->server->schemas(),
            $this,
            $query,
        );
    }
// laravel-json-api/core/src/Core/Schema/Schema.php

public static function model(): string
{
    if (isset(static::$model)) {
        $model = static::$model;
        
        if (property_exists(static::class, 'withScopes')) {
            foreach (static::$withScopes as $scope) {
                $model::addGlobalScope($scope);
            }
        }
        
        return static::$model;
    }

    throw new LogicException('The model class name must be set.');
}

I haven't looked much into how the package code works but something like that would allow to define with/without scopes inside the schema definition which would be most convenient. I can implement this feature if wanted. Is this a wanted feature and if so, what implementation would you recommend?

SEUH avatar May 09 '22 18:05 SEUH