Skip to main content

Field Dependency

It is quite common to have multiple relation fields in a form. For example, an Employee can be a member of multiple Projects.

When you select an employee in the form, you might only want to show projects where the employee is a member of.

Getting started

Let's start by defining two relational fields:

 BelongsTo::make('Employee', 'employee', Employee::class)
->rules('nullable', 'exists:employees,id'),

MorphMany::make('Addresses', 'addresses', Address::class)
->rules('nullable', 'exists:addresses,id')

Now when an employee is selected, we want the address select only to show related addresses.

For this example we just use 2 hardcoded id values:

MorphMany::make('Addresses', 'addresses', Address::class)
->rules('nullable', 'exists:addresses,id')
->dependsOn('employee', function (Builder $query, $employeeId) {
// If no employee is selected, just show all addresses as options
if (!$employeeId) {
return $query;
}

// Limit the address options
return $query->whereIn('addresses.id', [1, 5]);
})

The field you supply in the dependsOn method does not have to be a relation field:

Text::make(__('Name'), 'name')->setMaxWidth('sm'),

MorphMany::make('Addressen', 'addresses', Address::class)
->dependsOn('name', function (Builder $query, $name) {
if ($name === 'Laravel') {
return $query->whereIn('addresses.id', [1, 2]);
}

return $query->whereIn('addresses.id', [5,6]);
})

Automatically deselecting

When using ->dependsOn(...), Qore will try to automatically update the field state so it deselects the options based on query. If you want to disable this behaviour, you can pass false as the third argument:

->dependsOn(string $other, Closure $scope, bool $updateState = false)