Skip to content

Inconsistent behavior with relatableQueryUsing() accessing model fields #6092

@rpungello

Description

@rpungello
  • Laravel Version: 10.34.2
  • Nova Version: 4.32.6
  • PHP Version: 8.2.13
  • Database Driver & Version: MariaDB 10.11.4

Description:

We have a multi-tenant application, so within Nova we'd like for various fields to only pull from data belonging to the same company as the resource we're editing.

To do this, I have tried the following in our Nova Product resource. Product models have a distributor_id property that defines which company they're for.

BelongsTo::make('Default Type', 'defaultSampleType', SampleType::class)
    ->relatableQueryUsing(function (NovaRequest $request, Builder $query) {
        Log::debug("ID: $this->distributor_id");
        $query->where('distributor_id', '=', $this->distributor_id);
    })
    ->nullable()
    ->hideFromIndex(),

When I load the Product resource within Nova, three log entries are written, but nothing displays in the drop-down for "Default Type"

local.DEBUG: ID: 128
local.DEBUG: ID: 128
local.DEBUG: ID:

It seems like, for whatever reason, on the final load all the model properties are missing, which results in the menu checking for a null ID instead of the actual ID. The documentation for relatableQueryUsing() unfortunately only uses static data, so perhaps I'm just using this feature incorrectly, but the documentation makes no mention of how to factor in model properties so I was forced to guess.

I was able to make this work by using the following, but this results in an extra database query that shouldn't be necessary based on my understanding of how Nova handles model properties.

BelongsTo::make('Default Type', 'defaultSampleType', SampleType::class)
    ->relatableQueryUsing(function (NovaRequest $request, Builder $query) {
        $query->where('distributor_id', '=', ProductModel::whereId($request->resourceId)->value('distributor_id'));
    })
    ->nullable()
    ->hideFromIndex(),

Detailed steps to reproduce the issue on a fresh Nova installation:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions