Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow conditionally setting eager load #8

Merged
merged 1 commit into from
Jan 15, 2023
Merged

feat: allow conditionally setting eager load #8

merged 1 commit into from
Jan 15, 2023

Conversation

JaZo
Copy link
Contributor

@JaZo JaZo commented Jan 6, 2023

I'd like to conditionally allow/disallow eager loading, just like you can conditionally hide/show a field. A simple boolean would be enough in my use case, but to make it more in line with hidden and readOnly I've also added closure support. The only difference is that these closures receive a request and the new one doesn't as I couldn't find a good way to get the request.

N.B. I had first added the parameter to the existing cannotEagerLoad method, but that was pretty confusing due to the double negation.

Before

/**
 * @return \LaravelJsonApi\Contracts\Schema\Field[]
 */
public function fields(): array
{
    $userField = BelongsTo::make('user');
    if (Gate::denies('viewUser', Blog::class)) {
        $userField->cannotEagerLoad();
    }

    return [
        ID::make()->uuid(),
        $userField,
    ];
}

After

/**
 * @return \LaravelJsonApi\Contracts\Schema\Field[]
 */
public function fields(): array
{
    return [
        ID::make()->uuid(),
        BelongsTo::make('user')->canEagerLoad(Gate::allows('viewUser', Blog::class)),
    ];
}

Copy link
Contributor

@lindyhopchris lindyhopchris left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR, this looks like a good thing to add.

There's just one suggested change.

src/Core/Schema/Concerns/EagerLoadable.php Outdated Show resolved Hide resolved
@lindyhopchris lindyhopchris merged commit c33f0c8 into laravel-json-api:develop Jan 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants