diff --git a/src/Laravel/EloquentBuffer.php b/src/Laravel/EloquentBuffer.php index 08df728..52ceffd 100644 --- a/src/Laravel/EloquentBuffer.php +++ b/src/Laravel/EloquentBuffer.php @@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\Relations\MorphTo; use Tobyz\JsonApiServer\Context; use Tobyz\JsonApiServer\Schema\Field\Relationship; +use Tobyz\JsonApiServer\Schema\Field\ToMany; abstract class EloquentBuffer { @@ -56,7 +57,24 @@ public static function load( $modelClass = get_class($resource->newModel($context)); if ($resource instanceof EloquentResource && !isset($constrain[$modelClass])) { - $constrain[$modelClass] = fn($query) => $resource->scope($query, $context); + $constrain[$modelClass] = function ($query) use ( + $resource, + $context, + $relationship, + $relation, + ) { + $resource->scope($query, $context); + + // Limiting relationship results is only possible on Laravel 11 or later, + // or if the model uses the \Staudenmeir\EloquentEagerLimit\HasEagerLimit trait. + if ( + $relationship instanceof ToMany && + method_exists($relation, 'limit') && + !empty($relationship->limit) + ) { + $relation->limit($relationship->limit); + } + }; } } diff --git a/src/Schema/Field/ToMany.php b/src/Schema/Field/ToMany.php index 04d3405..dd85ef5 100644 --- a/src/Schema/Field/ToMany.php +++ b/src/Schema/Field/ToMany.php @@ -8,6 +8,8 @@ class ToMany extends Relationship { + public ?int $limit = null; + public function __construct(string $name) { parent::__construct($name); @@ -15,6 +17,13 @@ public function __construct(string $name) $this->type($name); } + public function limit(?int $limit): static + { + $this->limit = $limit; + + return $this; + } + public function serializeValue($value, Context $context): mixed { $meta = $this->serializeMeta($context);